]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - docs/proposed/magic-folder/remote-to-local-sync.rst
26f1825d4c56a68fc5efaf07b37e76b2340e617a
[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 Note that writing a file that does not already have an entry in
354 the `magic folder db`_ is initially classed as an overwrite.
355
356 A *write/download collision* occurs when another program writes
357 to ``foo`` in the local filesystem, concurrently with the new
358 version being written by the Magic Folder client. We need to
359 ensure that this does not cause data loss, as far as possible.
360
361 An important constraint on the design is that on Windows, it is
362 not possible to rename a file to the same name as an existing
363 file in that directory. Also, on Windows it may not be possible to
364 delete or rename a file that has been opened by another process
365 (depending on the sharing flags specified by that process).
366 Therefore we need to consider carefully how to handle failure
367 conditions.
368
369 In our proposed design, Alice's Magic Folder client follows
370 this procedure for an overwrite in response to a remote change:
371
372 1. Write a temporary file, say ``.foo.tmp``.
373 2. Use the procedure described in the `Fire Dragons_` section
374    to obtain an initial classification as an overwrite or a
375    conflict. (This takes as input the ``last_downloaded_uri``
376    field from the directory entry of the changed ``foo``.)
377 3. Set the ``mtime`` of the replacement file to be *T* seconds
378    before the current local time.
379 4. Perform a ''file replacement'' operation (explained below)
380    with backup filename ``foo.backup``, replaced file ``foo``,
381    and replacement file ``.foo.tmp``. If any step of this
382    operation fails, reclassify as a conflict and stop.
383
384 To reclassify as a conflict, attempt to rename ``.foo.tmp`` to
385 ``foo.conflicted``, suppressing errors.
386
387 The implementation of file replacement differs between Unix
388 and Windows. On Unix, it can be implemented as follows:
389
390 * 4a. Stat the replaced path, and set the permissions of the
391   replacement file to be the same as the replaced file,
392   bitwise-or'd with octal 600 (``rw-------``). If the replaced
393   file does not exist, set the permissions according to the
394   user's umask. If there is a directory at the replaced path,
395   fail.
396 * 4b. Attempt to move the replaced file (``foo``) to the
397   backup filename (``foo.backup``). If an ``ENOENT`` error
398   occurs because the replaced file does not exist, ignore this
399   error and continue with steps 4c and 4d.
400 * 4c. Attempt to create a hard link at the replaced filename
401   (``foo``) pointing to the replacement file (``.foo.tmp``).
402 * 4d. Attempt to unlink the replacement file (``.foo.tmp``),
403   suppressing errors.
404
405 Note that, if there is no conflict, the entry for ``foo``
406 recorded in the `magic folder db`_ will reflect the ``mtime``
407 set in step 3. The move operation in step 4b will cause a
408 ``MOVED_FROM`` event for ``foo``, and the link operation in
409 step 4c will cause an ``IN_CREATE`` event for ``foo``.
410 However, these events will not trigger an upload, because they
411 are guaranteed to be processed only after the file replacement
412 has finished, at which point the metadata recorded in the
413 database entry will exactly match the metadata for the file's
414 inode on disk. (The two hard links — ``foo`` and,  while it
415 still exists, ``.foo.tmp`` — share the same inode and
416 therefore the same metadata.)
417
418 .. _`magic folder db`: filesystem_integration.rst#local-scanning-and-database
419
420 On Windows, file replacement can be implemented by a call to
421 the `ReplaceFileW`_ API (with the
422 ``REPLACEFILE_IGNORE_MERGE_ERRORS`` flag). If an error occurs
423 because the replaced file does not exist, then we ignore this
424 error and attempt to move the replacement file to the replaced
425 file.
426
427 Similar to the Unix case, the `ReplaceFileW`_ operation will
428 cause one or more change notifications for ``foo``. The replaced
429 ``foo`` has the same ``mtime`` as the replacement file, and so any
430 such notification(s) will not trigger an unwanted upload.
431
432 .. _`ReplaceFileW`: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365512%28v=vs.85%29.aspx
433
434 To determine whether this procedure adequately protects against data
435 loss, we need to consider what happens if another process attempts to
436 update ``foo``, for example by renaming ``foo.other`` to ``foo``.
437 This requires us to analyze all possible interleavings between the
438 operations performed by the Magic Folder client and the other process.
439 (Note that atomic operations on a directory are totally ordered.)
440 The set of possible interleavings differs between Windows and Unix.
441
442 On Unix, for the case where the replaced file already exists, we have:
443
444 * Interleaving A: the other process' rename precedes our rename in
445   step 4b, and we get an ``IN_MOVED_TO`` event for its rename by
446   step 2. Then we reclassify as a conflict; its changes end up at
447   ``foo`` and ours end up at ``foo.conflicted``. This avoids data
448   loss.
449
450 * Interleaving B: its rename precedes ours in step 4b, and we do
451   not get an event for its rename by step 2. Its changes end up at
452   ``foo.backup``, and ours end up at ``foo`` after being linked there
453   in step 4c. This avoids data loss.
454
455 * Interleaving C: its rename happens between our rename in step 4b,
456   and our link operation in step 4c of the file replacement. The
457   latter fails with an ``EEXIST`` error because ``foo`` already
458   exists. We reclassify as a conflict; the old version ends up at
459   ``foo.backup``, the other process' changes end up at ``foo``, and
460   ours at ``foo.conflicted``. This avoids data loss.
461
462 * Interleaving D: its rename happens after our link in step 4c,
463   and causes an ``IN_MOVED_TO`` event for ``foo``. Its rename also
464   changes the ``mtime`` for ``foo`` so that it is different from
465   the ``mtime`` calculated in step 3, and therefore different
466   from the metadata recorded for ``foo`` in the magic folder db.
467   (Assuming no system clock changes, its rename will set an ``mtime``
468   timestamp corresponding to a time after step 4c, which is not
469   equal to the timestamp *T* seconds before step 4a, provided that
470   *T* seconds is sufficiently greater than the timestamp granularity.)
471   Therefore, an upload will be triggered for ``foo`` after its
472   change, which is correct and avoids data loss.
473
474 If the replaced file did not already exist, an ``ENOENT`` error
475 occurs at step 4b, and we continue with steps 4c and 4d. The other
476 process' rename races with our link operation in step 4c. If the
477 other process wins the race then the effect is similar to
478 Interleaving C, and if we win the race this it is similar to
479 Interleaving D. Either case avoids data loss.
480
481
482 On Windows, the internal implementation of `ReplaceFileW`_ is similar
483 to what we have described above for Unix; it works like this:
484
485 * 4a′. Copy metadata (which does not include ``mtime``) from the
486   replaced file (``foo``) to the replacement file (``.foo.tmp``).
487
488 * 4b′. Attempt to move the replaced file (``foo``) onto the
489   backup filename (``foo.backup``), deleting the latter if it
490   already exists.
491
492 * 4c′. Attempt to move the replacement file (``.foo.tmp``) to the
493   replaced filename (``foo``); fail if the destination already
494   exists.
495
496 Notice that this is essentially the same as the algorithm we use
497 for Unix, but steps 4c and 4d on Unix are combined into a single
498 step 4c′. (If there is a failure at steps 4c′ after step 4b′ has
499 completed, the `ReplaceFileW`_ call will fail with return code
500 ``ERROR_UNABLE_TO_MOVE_REPLACEMENT_2``. However, it is still
501 preferable to use this API over two `MoveFileExW`_ calls, because
502 it retains the attributes and ACLs of ``foo`` where possible.
503 Also note that if the `ReplaceFileW`_ call fails with
504 ``ERROR_FILE_NOT_FOUND`` because the replaced file does not exist,
505 then the replacment operation ignores this error and continues with
506 the equivalent of step 4c′, as on Unix.)
507
508 However, on Windows the other application will not be able to
509 directly rename ``foo.other`` onto ``foo`` (which would fail because
510 the destination already exists); it will have to rename or delete
511 ``foo`` first. Without loss of generality, let's say ``foo`` is
512 deleted. This complicates the interleaving analysis, because we
513 have two operations done by the other process interleaving with
514 three done by the magic folder process (rather than one operation
515 interleaving with four as on Unix).
516
517 So on Windows, for the case where the replaced file already exists,
518 we have:
519
520 * Interleaving A′: the other process' deletion of ``foo`` and its
521   rename of ``foo.other`` to ``foo`` both precede our rename in
522   step 4b. We get an event corresponding to its rename by step 2.
523   Then we reclassify as a conflict; its changes end up at ``foo``
524   and ours end up at ``foo.conflicted``. This avoids data loss.
525
526 * Interleaving B′: the other process' deletion of ``foo`` and its
527   rename of ``foo.other`` to ``foo`` both precede our rename in
528   step 4b. We do not get an event for its rename by step 2.
529   Its changes end up at ``foo.backup``, and ours end up at ``foo``
530   after being moved there in step 4c′. This avoids data loss.
531
532 * Interleaving C′: the other process' deletion of ``foo`` precedes
533   our rename of ``foo`` to ``foo.backup`` done by `ReplaceFileW`_,
534   but its rename of ``foo.other`` to ``foo`` does not, so we get
535   an ``ERROR_FILE_NOT_FOUND`` error from `ReplaceFileW`_ indicating
536   that the replaced file does not exist. We ignore this error and
537   attempt to move ``foo.tmp`` to ``foo``, racing with the other
538   process which is attempting to move ``foo.other`` to ``foo``.
539   If we win the race, then our changes end up at ``foo``, and the
540   other process' move fails. If the other process wins the race,
541   then its changes end up at ``foo``, our move fails, and we
542   reclassify as a conflict, so that our changes end up at
543   ``foo.conflicted``. Either possibility avoids data loss.
544
545 * Interleaving D′: the other process' deletion and/or rename happen
546   during the call to `ReplaceFileW`_, causing the latter to fail.
547   There are two subcases:
548
549   * if the error is ``ERROR_UNABLE_TO_MOVE_REPLACEMENT_2``, then
550     ``foo`` is renamed to ``foo.backup`` and ``.foo.tmp`` remains
551     at its original name after the call.
552   * for all other errors, ``foo`` and ``.foo.tmp`` both remain at
553     their original names after the call.
554
555   In both subcases, we reclassify as a conflict and rename ``.foo.tmp``
556   to ``foo.conflicted``. This avoids data loss.
557
558 * Interleaving E′: the other process' deletion of ``foo`` and attempt
559   to rename ``foo.other`` to ``foo`` both happen after all internal
560   operations of `ReplaceFileW`_ have completed. This causes deletion
561   and rename events for ``foo`` (which will in practice be merged due
562   to the pending delay, although we don't rely on that for correctness).
563   The rename also changes the ``mtime`` for ``foo`` so that it is
564   different from the ``mtime`` calculated in step 3, and therefore
565   different from the metadata recorded for ``foo`` in the magic folder
566   db. (Assuming no system clock changes, its rename will set an
567   ``mtime`` timestamp corresponding to a time after the internal
568   operations of `ReplaceFileW`_ have completed, which is not equal to
569   the timestamp *T* seconds before `ReplaceFileW`_ is called, provided
570   that *T* seconds is sufficiently greater than the timestamp
571   granularity.) Therefore, an upload will be triggered for ``foo``
572   after its change, which is correct and avoids data loss.
573
574 .. _`MoveFileExW`: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365240%28v=vs.85%29.aspx
575
576 If the replaced file did not already exist, we get an
577 ``ERROR_FILE_NOT_FOUND`` error from `ReplaceFileW`_, and attempt to
578 move ``foo.tmp`` to ``foo``. This is similar to Interleaving C, and
579 either possibility for the resulting race avoids data loss.
580
581 We also need to consider what happens if another process opens ``foo``
582 and writes to it directly, rather than renaming another file onto it:
583
584 * On Unix, open file handles refer to inodes, not paths. If the other
585   process opens ``foo`` before it has been renamed to ``foo.backup``,
586   and then closes the file, changes will have been written to the file
587   at the same inode, even if that inode is now linked at ``foo.backup``.
588   This avoids data loss.
589
590 * On Windows, we have two subcases, depending on whether the sharing
591   flags specified by the other process when it opened its file handle
592   included ``FILE_SHARE_DELETE``. (This flag covers both deletion and
593   rename operations.)
594
595   i.  If the sharing flags *do not* allow deletion/renaming, the
596       `ReplaceFileW`_ operation will fail without renaming ``foo``.
597       In this case we will end up with ``foo`` changed by the other
598       process, and the downloaded file still in ``foo.tmp``.
599       This avoids data loss.
600
601   ii. If the sharing flags *do* allow deletion/renaming, then
602       data loss or corruption may occur. This is unavoidable and
603       can be attributed to other process making a poor choice of
604       sharing flags (either explicitly if it used `CreateFile`_, or
605       via whichever higher-level API it used).
606
607 .. _`CreateFile`: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx
608
609 Note that it is possible that another process tries to open the file
610 between steps 4b and 4c (or 4b′ and 4c′ on Windows). In this case the
611 open will fail because ``foo`` does not exist. Nevertheless, no data
612 will be lost, and in many cases the user will be able to retry the
613 operation.
614
615 Above we only described the case where the download was initially
616 classified as an overwrite. If it was classed as a conflict, the
617 procedure is the same except that we choose a unique filename
618 for the conflicted file (say, ``foo.conflicted_unique``). We write
619 the new contents to ``.foo.tmp`` and then rename it to
620 ``foo.conflicted_unique`` in such a way that the rename will fail
621 if the destination already exists. (On Windows this is a simple
622 rename; on Unix it can be implemented as a link operation followed
623 by an unlink, similar to steps 4c and 4d above.) If this fails
624 because another process wrote ``foo.conflicted_unique`` after we
625 chose the filename, then we retry with a different filename.
626
627
628 Read/download collisions
629 ~~~~~~~~~~~~~~~~~~~~~~~~
630
631 A *read/download collision* occurs when another program reads
632 from ``foo`` in the local filesystem, concurrently with the new
633 version being written by the Magic Folder client. We want to
634 ensure that any successful attempt to read the file by the other
635 program obtains a consistent view of its contents.
636
637 On Unix, the above procedure for writing downloads is sufficient
638 to achieve this. There are three cases:
639
640 * A. The other process opens ``foo`` for reading before it is
641   renamed to ``foo.backup``. Then the file handle will continue to
642   refer to the old file across the rename, and the other process
643   will read the old contents.
644
645 * B. The other process attempts to open ``foo`` after it has been
646   renamed to ``foo.backup``, and before it is linked in step c.
647   The open call fails, which is acceptable.
648
649 * C. The other process opens ``foo`` after it has been linked to
650   the new file. Then it will read the new contents.
651
652 On Windows, the analysis is very similar, but case A′ needs to
653 be split into two subcases, depending on the sharing mode the other
654 process uses when opening the file for reading:
655
656 * A′. The other process opens ``foo`` before the Magic Folder
657   client's attempt to rename ``foo`` to ``foo.backup`` (as part
658   of the implementation of `ReplaceFileW`_). The subcases are:
659
660   i.  The other process uses sharing flags that deny deletion and
661       renames. The `ReplaceFileW`_ call fails, and the download is
662       reclassified as a conflict. The downloaded file ends up at
663       ``foo.conflicted``, which is correct.
664
665   ii. The other process uses sharing flags that allow deletion
666       and renames. The `ReplaceFileW`_ call succeeds, and the
667       other process reads inconsistent data. This can be attributed
668       to a poor choice of sharing flags by the other process.
669
670 * B′. The other process attempts to open ``foo`` at the point
671   during the `ReplaceFileW`_ call where it does not exist.
672   The open call fails, which is acceptable.
673
674 * C′. The other process opens ``foo`` after it has been linked to
675   the new file. Then it will read the new contents.
676
677
678 For both write/download and read/download collisions, we have
679 considered only interleavings with a single other process, and
680 only the most common possibilities for the other process'
681 interaction with the file. If multiple other processes are
682 involved, or if a process performs operations other than those
683 considered, then we cannot say much about the outcome in general;
684 however, we believe that such cases will be much less common.
685
686
687
688 Fire Dragons: Distinguishing conflicts from overwrites
689 ''''''''''''''''''''''''''''''''''''''''''''''''''''''
690
691 When synchronizing a file that has changed remotely, the Magic Folder
692 client needs to distinguish between overwrites, in which the remote
693 side was aware of your most recent version and overwrote it with a
694 new version, and conflicts, in which the remote side was unaware of
695 your most recent version when it published its new version. Those two
696 cases have to be handled differently — the latter needs to be raised
697 to the user as an issue the user will have to resolve and the former
698 must not bother the user.
699
700 For example, suppose that Alice's Magic Folder client sees a change
701 to ``foo`` in Bob's DMD. If the version it downloads from Bob's DMD
702 is "based on" the version currently in Alice's local filesystem at
703 the time Alice's client attempts to write the downloaded file ‒or if
704 there is no existing version in Alice's local filesystem at that time‒
705 then it is an overwrite. Otherwise it is initially classified as a
706 conflict.
707
708 This initial classification is used by the procedure for writing a
709 file described in the `Earth Dragons`_ section above. As explained
710 in that section, we may reclassify an overwrite as a conflict if an
711 error occurs during the write procedure.
712
713 .. _`Earth Dragons`: #earth-dragons-collisions-between-local-filesystem-operations-and-downloads
714
715 In order to implement this policy, we need to specify how the
716 "based on" relation between file versions is recorded and updated.
717
718 We propose to record this information:
719
720 * in the `magic folder db`_, for local files;
721 * in the Tahoe-LAFS directory metadata, for files stored in the
722   Magic Folder.
723
724 In the magic folder db we will add a *last-downloaded record*,
725 consisting of ``last_downloaded_uri`` and ``last_downloaded_timestamp``
726 fields, for each path stored in the database. Whenever a Magic Folder
727 client downloads a file, it stores the downloaded version's URI and
728 the current local timestamp in this record. Since only immutable
729 files are used, the URI will be an immutable file URI, which is
730 deterministically and uniquely derived from the file contents and
731 the Tahoe-LAFS node's `convergence secret`_.
732
733 (Note that the last-downloaded record is updated regardless of
734 whether the download is an overwrite or a conflict. The rationale
735 for this to avoid "conflict loops" between clients, where every
736 new version after the first conflict would be considered as another
737 conflict.)
738
739 .. _`convergence secret`: https://tahoe-lafs.org/trac/tahoe-lafs/browser/docs/convergence-secret.rst
740
741 Later, in response to a local filesystem change at a given path, the
742 Magic Folder client reads the last-downloaded record associated with
743 that path (if any) from the database and then uploads the current
744 file. When it links the uploaded file into its client DMD, it
745 includes the ``last_downloaded_uri`` field in the metadata of the
746 directory entry, overwriting any existing field of that name. If
747 there was no last-downloaded record associated with the path, this
748 field is omitted.
749
750 Note that ``last_downloaded_uri`` field does *not* record the URI of
751 the uploaded file (which would be redundant); it records the URI of
752 the last download before the local change that caused the upload.
753 The field will be absent if the file has never been downloaded by
754 this client (i.e. if it was created on this client and no change
755 by any other client has been detected).
756
757 A possible refinement also takes into account the
758 ``last_downloaded_timestamp`` field from the magic folder db, and
759 compares it to the timestamp of the change that caused the upload
760 (which should be later, assuming no system clock changes).
761 If the duration between these timestamps is very short, then we
762 are uncertain about whether the process on Bob's system that wrote
763 the local file could have taken into account the last download.
764 We can use this information to be conservative about treating
765 changes as conflicts. So, if the duration is less than a configured
766 threshold, we omit the ``last_downloaded_uri`` field from the
767 metadata. This will have the effect of making other clients treat
768 this change as a conflict whenever they already have a copy of the
769 file.
770
771 Now we are ready to describe the algorithm for determining whether a
772 download for the file ``foo`` is an overwrite or a conflict (refining
773 step 2 of the procedure from the `Earth Dragons`_ section).
774
775 Let ``last_downloaded_uri`` be the field of that name obtained from
776 the directory entry metadata for ``foo`` in Bob's DMD (this field
777 may be absent). Then the algorithm is:
778
779 * 2a. If Alice has no local copy of ``foo``, classify as an overwrite.
780
781 * 2b. Otherwise, "stat" ``foo`` to get its *current statinfo* (size
782   in bytes, ``mtime``, and ``ctime``).
783
784 * 2c. Read the following information for the path ``foo`` from the
785   local magic folder db:
786
787   * the *last-uploaded statinfo*, if any (this is the size in
788     bytes, ``mtime``, and ``ctime`` stored in the ``local_files``
789     table when the file was last uploaded);
790   * the ``last_uploaded_uri`` field of the ``local_files`` table
791     for this file, which is the URI under which the file was last
792     uploaded.
793
794 * 2d. If any of the following are true, then classify as a conflict:
795
796   * there are pending notifications of changes to ``foo``;
797   * the last-uploaded statinfo is either absent, or different
798     from the current statinfo;
799   * either ``last_downloaded_uri`` or ``last_uploaded_uri``
800     (or both) are absent, or they are different.
801
802   Otherwise, classify as an overwrite.
803
804
805 Air Dragons: Collisions between local writes and uploads
806 ''''''''''''''''''''''''''''''''''''''''''''''''''''''''
807
808 Short of filesystem-specific features on Unix or the `shadow copy service`_
809 on Windows (which is per-volume and therefore difficult to use in this
810 context), there is no way to *read* the whole contents of a file
811 atomically. Therefore, when we read a file in order to upload it, we
812 may read an inconsistent version if it was also being written locally.
813
814 .. _`shadow copy service`: https://technet.microsoft.com/en-us/library/ee923636%28v=ws.10%29.aspx
815
816 A well-behaved application can avoid this problem for its writes:
817
818 * On Unix, if another process modifies a file by renaming a temporary
819   file onto it, then we will consistently read either the old contents
820   or the new contents.
821 * On Windows, if the other process uses sharing flags to deny reads
822   while it is writing a file, then we will consistently read either
823   the old contents or the new contents, unless a sharing error occurs.
824   In the case of a sharing error we should retry later, up to a
825   maximum number of retries.
826
827 In the case of a not-so-well-behaved application writing to a file
828 at the same time we read from it, the magic folder will still be
829 eventually consistent, but inconsistent versions may be visible to
830 other users' clients.
831
832 In Objective 2 we implemented a delay, called the *pending delay*,
833 after the notification of a filesystem change and before the file is
834 read in order to upload it (Tahoe-LAFS ticket `#1440`_). If another
835 change notification occurs within the pending delay time, the delay
836 is restarted. This helps to some extent because it means that if
837 files are written more quickly than the pending delay and less
838 frequently than the pending delay, we shouldn't encounter this
839 inconsistency.
840
841 .. _`#1440`: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1440
842
843 The likelihood of inconsistency could be further reduced, even for
844 writes by not-so-well-behaved applications, by delaying the actual
845 upload for a further period —called the *stability delay*— after the
846 file has finished being read. If a notification occurs between the
847 end of the pending delay and the end of the stability delay, then
848 the read would be aborted and the notification requeued.
849
850 This would have the effect of ensuring that no write notifications
851 have been received for the file during a time window that brackets
852 the period when it was being read, with margin before and after
853 this period defined by the pending and stability delays. The delays
854 are intended to account for asynchronous notification of events, and
855 caching in the filesystem.
856
857 Note however that we cannot guarantee that the delays will be long
858 enough to prevent inconsistency in any particular case. Also, the
859 stability delay would potentially affect performance significantly
860 because (unlike the pending delay) it is not overlapped when there
861 are multiple files on the upload queue. This performance impact
862 could be mitigated by uploading files in parallel where possible
863 (Tahoe-LAFS ticket `#1459`_).
864
865 We have not yet decided whether to implement the stability delay, and
866 it is not planned to be implemented for the OTF objective 4 milestone.
867 Ticket `#2431`_ has been opened to track this idea.
868
869 .. _`#1459`: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1459
870 .. _`#2431`: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/2431
871
872 Note that the situation of both a local process and the Magic Folder
873 client reading a file at the same time cannot cause any inconsistency.
874
875
876 Water Dragons: Handling deletion and renames
877 ''''''''''''''''''''''''''''''''''''''''''''
878
879 Deletion of a file
880 ~~~~~~~~~~~~~~~~~~
881
882 When a file is deleted from the filesystem of a Magic Folder client,
883 the most intuitive behavior is for it also to be deleted under that
884 name from other clients. To avoid data loss, the other clients should
885 actually rename their copies to a backup filename.
886
887 It would not be sufficient for a Magic Folder client that deletes
888 a file to implement this simply by removing the directory entry from
889 its DMD. Indeed, the entry may not exist in the client's DMD if it
890 has never previously changed the file.
891
892 Instead, the client links a zero-length file into its DMD and sets
893 ``deleted: true`` in the directory entry metadata. Other clients
894 take this as a signal to rename their copies to the backup filename.
895
896 Note that the entry for this zero-length file has a version number as
897 usual, and later versions may restore the file.
898
899 When the downloader deletes a file (or renames it to a filename
900 ending in ``.backup``) in response to a remote change, a local
901 filesystem notification will occur, and we must make sure that this
902 is not treated as a local change. To do this we have the downloader
903 set the ``size`` field in the magic folder db to ``None`` (SQL NULL)
904 just before deleting the file, and suppress notifications for which
905 the local file does not exist, and the recorded ``size`` field is
906 ``None``.
907
908 When a Magic Folder client restarts, we can detect files that had
909 been downloaded but were deleted while it was not running, because
910 their paths will have last-downloaded records in the magic folder db
911 with a ``size`` other than ``None``, and without any corresponding
912 local file.
913
914 Deletion of a directory
915 ~~~~~~~~~~~~~~~~~~~~~~~
916
917 Local filesystems (unlike a Tahoe-LAFS filesystem) normally cannot
918 unlink a directory that has any remaining children. Therefore a
919 Magic Folder client cannot delete local copies of directories in
920 general, because they will typically contain backup files. This must
921 be done manually on each client if desired.
922
923 Nevertheless, a Magic Folder client that deletes a directory should
924 set ``deleted: true`` on the metadata entry for the corresponding
925 zero-length file. This avoids the directory being recreated after
926 it has been manually deleted from a client.
927
928 Renaming
929 ~~~~~~~~
930
931 It is sufficient to handle renaming of a file by treating it as a
932 deletion and an addition under the new name.
933
934 This also applies to directories, although users may find the
935 resulting behavior unintuitive: all of the files under the old name
936 will be renamed to backup filenames, and a new directory structure
937 created under the new name. We believe this is the best that can be
938 done without imposing unreasonable implementation complexity.
939
940
941 Summary
942 -------
943
944 This completes the design of remote-to-local synchronization.
945 We realize that it may seem very complicated. Anecdotally, proprietary
946 filesystem synchronization designs we are aware of, such as Dropbox,
947 are said to incur similar or greater design complexity.