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