Repository navigation
Conversation
- The DS saves each message to private/spool/<peer>/ before any network call, and removes it once the DO has it. The upload downgrades and encrypts the message, so it uses the DO's protocol and key at that time. - A push and sync() upload the saved messages oldest first, under a lock, so that the notebook and syft-bg do not upload a message twice. P2PConnection.is_delivered() finds a message that an upload sent before the process stopped, so it is not sent again. - The file hashes advance when a message is saved, not when it is sent, so a second edit made offline builds on the first. - A message to a peer that is not ready stays saved. The push raises and says so, and sync() warns for each peer that waits. The "not known" remedy no longer says "send again". - A spool entry carries a version, and an entry of a later version is refused.
…a lost connection - After a restart, the DS records the hashes of its saved messages again. The next edit of a path then builds on a saved edit that is not sent yet. The DO then does not refuse it as outdated. - sync() pulls before it uploads the saved messages, so a message that cannot go never holds back the results. - DriveP2PConnection.send raises ConnectionUnavailableError when Drive cannot be reached. A push then says that the change is saved and that the next sync sends it, so the user does not submit the job again. - The crash test also covers a message that the DO already archived.
… errors - SpoolEntry.message is now compressed_message, because it holds the compressed bytes of the message. - Spool.pending() is now pending_messages(). - In DatasiteWatcherSyncer, waiting is now not_ready_errors. It maps each recipient email to the error that says why its messages wait.
- P2PConnection.is_delivered() is gone. The WebRTC connection has no record of receipts after a restart, so it could not answer, and it could not be built without the method. - send() may be repeated with the same msg_id, and the peer applies the message once. Drive's send() skips a proposal that it already uploaded. The WebRTC queue already drops a repeated id while the message waits. - The spool sends each saved message and then removes it, with no separate check.
…ion check - read_versioned_json() in syft/sync/utils/versioned_file.py reads a JSON file and refuses a later version before it checks the fields. - SpoolEntry.read() and _DatasiteSettings.read() call it. Their error messages do not change.
- WatcherCheckpoint and WatcherRollingState in syft/sync/checkpoints/watcher_state.py hold the files received from one DO, the changes since then and the cursor in its outbox. They refuse a state that a later client wrote. - parse_versioned_json() checks the version of JSON text or bytes before the fields. read_versioned_json() now calls it for a file. - DriveWatcherStoreConnection keeps one folder per DO in /SyftBox/<me>-<version>-watcher-state, which is shared with nobody. A save replaces the content of the checkpoint file or the rolling-state file in place. - put_checkpoint() and put_rolling_state() take no file name, because each DO has one file of each kind.
…crypted with the DS key - watcher_save_checkpoint() and watcher_save_rolling_state() encrypt the state for the DS when encryption is required, then store it. - watcher_load_checkpoint() and watcher_load_rolling_state() return None only when nothing is saved. They raise when the state cannot be decrypted or a later client saved it. - When the DS key cannot decrypt the state, the error tells the DS to log in with the key_file of the key that saved it.
…at startup - At startup, a DS in on-disk mode restores every DO that has saved state. It writes the files of the checkpoint and the rolling state, and records their hashes and the received message ids. - After a pull that receives messages, the DS saves the rolling state of that DO, then marks the messages processed. At 50 changed paths, it folds them into the checkpoint. - The DS keeps the received message ids per DO. An event that pre_write_filter refuses is not saved, so a restore does not write it. - WatcherRollingState has no last_msg_id, because the cursor is the newest received id. - peers_with_saved_state() lists the DOs that have saved state.
… holds its state - In on-disk mode, the DS keeps its record of received messages in memory, as in-memory mode does. A restart restores only from the saved state on Drive. - The code that rebuilt the cursor and the file hashes from the local folder is gone, and so is the unused events_base_path. - The local cleanup no longer deletes a -event-messages folder. - The three tests that restarted from the local folder now check the state restored from Drive.
…checkpoint models - Watcher state is not encrypted until key recovery exists, as the ticket says. With the DS key, an enclave could not boot twice: its new key could not read the state of the last boot. - The DS saves a Checkpoint and a RollingState from syft/sync/checkpoints/, as the ticket says. watcher_state.py and parse_versioned_json are gone. - CheckpointFile.content holds str or bytes, so a binary file survives a checkpoint. RollingState.received_msg_ids holds the ids that a DS received. - The DS saves and loads the state of a DO under its email without case, so two spellings share one Drive folder. A restore writes the checkpoint files under the email as the DO's events spell it.
- Such a change blocked every later sync of the DS. A change with no hash made each fold raise, and a change with no content raised when it was applied. - The DS now drops it with a warning, as it does for an event aimed at another datasite.
…e DO and the DS - syft/sync/utils/file_content.py holds the text-or-bytes content code that ProposedFileChange, FileChangeEvent and CheckpointFile used to repeat. The JSON shape does not change. - Checkpoint.with_events() applies events to a checkpoint. The DO compaction and the DS fold both use it, and compact_incremental_checkpoints is gone. - The DO compaction now raises on a change without content or hash. Before, it dropped the file and could write "None" as a hash.
- decode_content() dropped characters outside the base64 alphabet and returned other bytes, with no error. It now raises, so the model refuses the content.
- DEFAULT_CHECKPOINT_EVENT_THRESHOLD moved to syft/sync/checkpoints/checkpoint.py. The DO syncer, the DS cache and SyftboxManager all read it. - WATCHER_CHECKPOINT_THRESHOLD and three literal defaults of 50 in SyftboxManager are gone.
- DriveWatcherStoreConnection.clone_for_thread() returned the same object, so another thread would share one Drive client. It now returns a store over a new client, as the other Drive connections do.
…ndle - WatcherStoreConnection.latest_checkpoint() is now get_checkpoint(), because each DO has one checkpoint. put_checkpoint() and put_rolling_state() return nothing, because no caller read the file id. - DriveWatcherStoreConnection names its helpers after the watcher folder and the files: _watcher_folder_id(), _save_file(), _read_file() and _find_id(). - DataSiteWatcherCache has _save_watcher_state() and _restore_watcher_state(). The DO compaction names its sorted checkpoints incrementals_in_order.
…test - test_ds_cache_handles_deletions_correctly reloaded over an empty mock Drive, so it passed even with no restore. It now reloads over the DS's own router. - The test also checks that a kept file comes back, so a restore that does nothing fails it.
| # The compressed message, before the downgrade and the encryption for its peer. | ||
| compressed_message: bytes |
There was a problem hiding this comment.
SpoolEntry stores the whole compressed message, so every saved entry carries the full contents of every file it changes.
We probably don't want to store the file contents in the spool/queue, because the contents can be very large. We don't need to implement this completely now, but we should make sure we prepare it in such a way that it's not a lot of work later. It will probably work with references to the content and streaming in the future. Let's make that easy now.
| def _record_spooled_hashes(self) -> None: | ||
| """Record the hashes of the saved messages, so that a change after a | ||
| restart builds on a saved change that is not sent yet.""" | ||
| for recipient in self.spool.recipients(): | ||
| for message in self.spool.pending_messages(recipient): |
There was a problem hiding this comment.
When the DS manager is built, _record_spooled_hashes() loads every saved message in full and records the file hashes stored in it, so an edit after a restart builds on a saved edit that was not sent yet.
Loading every saved message on startup is a bit heavy. What happens if we have multi-GB files in there (that may not fit in memory)? We could store multiple things like last modified and file size as a heuristic for larger files (or in general?).
- Drive's send() no longer makes an extra Drive call before each proposal upload. The call found a copy that a stop between the upload and Spool.remove() left behind. - The DO already refuses that copy: its old hash no longer matches, so the DO archives it with a warning and applies the change once. - The crash test checks that the DO applies the job once.
…ueue - DatasiteWatcherSyncer.push_file_changes() takes a list of files. It saves one message per datasite to the spool, then uploads. The in-memory queue, process_now and process_file_changes_queue() are gone, so the spool is the only place that holds outgoing changes. - push_job_files() passes every file of the job in one call, so a job is still one message. on_file_change() passes one file. - A test checks that a job of three files is one spool entry and one message in the DO's inbox.
- A spool entry is now a folder. entry.json holds the message without the content of its files, and each content is in its own file next to it. add() writes entry.json last and remove() deletes it first, so a folder without it is not an entry. - Startup reads only entry.json to record the saved hashes. The upload loads one message at a time, so large files are not all in memory at once. - SPOOL_ENTRY_VERSION is 2.
- DriveWatcherStoreConnection keeps the ids of the watcher folder, of each DO folder and of each file once it finds or creates them. After the first save, a save is one Drive call and a load is one download. Before, each save looked up three ids first. - reset(peer) drops the ids of that DO, reset_caches() drops all of them, and clone_for_thread() copies them.
…the DS - FileChangeEvent refuses a change that is not a delete and has no content or no hash. No code builds one, and a message that holds one cannot be read: the DS skips it with a warning, as any unreadable outbox message. - The DS no longer checks each event for content. _accepted_events() is _events_within_peer_datasite() again. - Checkpoint.with_events() keeps its check as a guard of that rule.
- CheckpointFile.content is always bytes, as base64 in JSON. A checkpoint built from text encodes it as UTF-8, so the hashes do not change. - The content_type field and its two hooks are gone from CheckpointFile. Events and proposals keep str or bytes, because peers exchange them.
- The router encrypts the watcher state with the DS key when the DS requires encryption, as it does the DO's own state. A key that cannot decrypt it raises an error that says to log in with the key_file of the key that saved it. - persist_watcher_state, next to persist_owner_state, turns the watcher state on or off, in both cache modes. An enclave gets a new key at each boot, so for_enclave() sets both from the same setting, which is off by default. - The in-memory cache now saves and restores the watcher state too, so test clients run it as a real client does.
- peers_with_saved_state() no longer fills the folder-id cache from its listing. That listing skipped the check that a DO has exactly one folder, so two folders made at the same time were read as one without an error. - The test of the id cache counts Drive calls with _count_drive_calls(), which sees every list request.
…_content - file_content.content_bytes() encodes text as UTF-8. The checkpoint and the send queue use it, instead of a copy each. - The send queue reads ContentType from file_content, instead of its own copy.
- push_file_changes() saves the messages through _queue_file_changes(), which returns only the recipients. The content of the files is freed before the upload, which reads each message back from the send queue, so a push no longer holds the whole job in memory while it uploads. - A test counts the copies of the content that are alive during the upload.
- With freeze_private_datasets on, the watcher does not change or delete a file that it already has in an immutable collection. - The enclave flow turns the flag on, so syft_enclaves.immutability is gone.
feat: keep the DS's watcher state on its own Drive and restore it at startup
# Conflicts: # packages/syft-enclave/src/syft_enclaves/client.py # packages/syft-enclave/src/syft_enclaves/immutability.py # tests/migrations/unit/test_file_change_events_serialization.py
| def __init__(self, folder: Path): | ||
| self.folder = folder | ||
|
|
||
| def add(self, recipient: str, message: ProposedFileChangesMessage) -> None: |
There was a problem hiding this comment.
SendQueue.add() saves each change's content to its own <index>.content file in the message's folder, then writes entry.json.
I think when we add changes to the queue we should only pass the file paths (from push_file_changes onwards). Then we can also just store the file paths in the SendQueue, and not the contents. Then when we read from the queue, we read the file paths and we can batch files into a message until the message reaches a certain size (max message size).
| self.queue.put((relative_path, content)) | ||
| if process_now: | ||
| self.process_file_changes_queue() | ||
| self, relative_path: Path | str, content: str | bytes | None = None |
There was a problem hiding this comment.
on_file_change() no longer takes process_now: every change is saved to the send queue and uploaded straight away through push_file_changes().
I think it would still be useful to keep the process_now arg. When we are moving this to the background processes we will need 2 processes, one that writes to the queue when a file changes and one that syncs.
| self._record_proposed_hashes(message) | ||
| return list(changes_by_recipient) | ||
|
|
||
| def _record_proposed_hashes(self, message: ProposedFileChangesMessage) -> None: |
There was a problem hiding this comment.
Let's rename to local hashes, e.g. _record_local_hashes().
| datasite_send_queue_path(config.syftbox_folder, config.email) | ||
| ), | ||
| ) | ||
| syncer._record_queued_hashes() |
There was a problem hiding this comment.
_record_queued_hashes() records the hashes of the changes still in the send queue at startup, but only DatasiteWatcherSyncer.from_config() calls it.
This is not the right place, it should happen regardless of the init method.
| event_count += len(event_message.events) | ||
| self._record_received(peer_email, raw.msg_id) | ||
| if received and self.persist_watcher_state: | ||
| self._save_watcher_state(peer_email) |
There was a problem hiding this comment.
sync_down() now saves each DO's state only to the DS's Drive, through _save_watcher_state(), before it marks the messages processed. The local <syftbox>-event-messages folder is gone, and events_connection is in memory only.
- When we receive messages, I think we should still store messages both locally and remotely. Storing locally can be done by storing the checkpoints as well.
_fold_into_checkpointis a weird name, fold what?_save_watcher_statedoesn't say it's remotely.- It looks like
events_connectionand the rolling state now basically do the same thing. I think we could perhaps only keep the rolling state, however it should be persisted to disk.
| # The msg_ids of the events messages received from each peer, keyed by | ||
| # ``_peer_key``. The connection lists back a bit before the last one for | ||
| # late messages, and skips these. | ||
| received_msg_ids_per_peer: Dict[str, Set[str]] = {} |
There was a problem hiding this comment.
The received message ids live only in received_msg_ids_per_peer. _save_rolling_state() copies them into the saved RollingState and _restore_rolling_state() clears them again, because _fold_into_checkpoint() starts a new empty RollingState.
There's a cleaner way. Make RollingState.received_msg_ids the only copy, and keep only the ids that are still needed:
- One copy:
_record_received()adds each id straight to the data owner'sRollingState._fold_into_checkpoint()passes the ids into the new emptyRollingState, so the fold doesn't wipe them. - Keep only recent ids: the ids are only needed to skip messages already read when the outbox is listed again for the last 60 seconds (
OUTBOX_LOOKBACK_SECONDS). So_record_received()can drop any id more than 60 seconds older than the newest. The list then stays small, which also stopsrolling_state.tar.gzfrom growing with every message. - What gets deleted:
received_msg_ids_per_peer, the copy-in in_save_rolling_state(), the clear in_restore_rolling_state(), and probablylast_msg_id_per_peertoo, since the last id is just the newest one in the list.
| ) | ||
| self.connection_router.watcher_save_rolling_state(key, saved) | ||
|
|
||
| def _rolling_state_local(self, peer_email: str) -> RollingState: |
There was a problem hiding this comment.
_rolling_state_local() returns a DO's in-memory RollingState, and creates an empty one the first time it is asked.
I don't love this pattern. The rolling state could be set up once, when a peer is loaded or added. What that would look like:
- Add
DataSiteWatcherCache.init_peer_state(peer_email). It restores the owner's saved checkpoint and rolling state if there are any, and otherwise creates an emptyRollingState. - Have the manager call it for each new peer after
load_peers(), and inadd_peer(). Skip it whenpersist_watcher_stateis off. _rolling_state_local()becomes a plain dict lookup that raises for an unknown peer, which also follows the "raise by default" guideline.
| ): | ||
| self._fold_into_checkpoint(peer_email) | ||
|
|
||
| def _fold_into_checkpoint(self, peer_email: str) -> None: |
There was a problem hiding this comment.
Every 50 changes, _fold_into_checkpoint() downloads the DO's whole checkpoint, merges in the changes and uploads it again, so the DS keeps one checkpoint per DO. The DO itself keeps a full checkpoint plus incremental checkpoints, compacted at 4.
I don't see why we are not consistent with the DO and use incremental checkpoints?
| self.file_hashes[path_key] = event.new_hash | ||
| cache._load_collection_hashes_from_disk() | ||
| if cache.persist_watcher_state: | ||
| cache._restore_watcher_state() |
There was a problem hiding this comment.
DataSiteWatcherCache.from_config() restores each DO's checkpoint and rolling state from the DS's Drive, for the in-memory and on-disk caches both.
This logic should not live in the from_config method, but happen in or after the init.
| update={"received_msg_ids": []} | ||
| ) | ||
|
|
||
| def _restore_file(self, datasite_email: str, file: CheckpointFile) -> None: |
There was a problem hiding this comment.
Rename to _restore_checkpoint_file().
| if checkpoint is None: | ||
| # Live events write under the email as the DO's events spell it, so | ||
| # a restore writes the checkpoint files there too. | ||
| checkpoint = Checkpoint(email=rolling_state.events[-1].datasite_email) |
There was a problem hiding this comment.
A new checkpoint takes the DO's email as spelled in the DO's events, so the folder name comes from the message, not from the peer entry. We want all emails lowercase, and the email should come from the peer info.
When _events_within_peer_datasite() accepts an event, set its datasite_email to the lowercase peer email.
- The file path,
file_hashes, the rolling state and the checkpoint then all use the lowercase folder. _fold_into_checkpoint()can create the checkpoint withCheckpoint(email=key), and theevents[-1].datasite_emailline and its comment go away.test_restore_writes_files_where_events_writewould then check that the file lands in the lowercase folder.
| token_path=Path(token_path) if token_path is not None else None, | ||
| encryption=True, | ||
| persist_owner_state=persist_owner_state, | ||
| persist_watcher_state=persist_owner_state, |
There was a problem hiding this comment.
persist_watcher_state should just be independent of persist_owner_state.
Summary
"connsplit v1.3: Scientist durability". This PR now also holds #9613, which was stacked on it and merged into this branch.
<syftbox>/<ds email>/private/send_queue/<do email>/<msg_id>/, then uploads it, and removes it once the upload succeeds. The upload downgrades and encrypts the message with the DO's protocol and key at that time.client.sync()uploads it after the pull, oldest first, under a file lock. The push error says the change is saved, andsync()warns for each DO that cannot receive yet.push_job_filespasses all files topush_file_changesin one call. The job still goes as one message, and its content is read back from disk one message at a time.<syftbox>-event-messagesfolder. Now the DS saves its state for that DO on its own Drive, in/SyftBox/<email>-<version>-watcher-state/<do email>/, before it marks the messages processed.rolling_state.tar.gzholds the changes since the checkpoint and the received message ids. At 50 changed paths, they fold intocheckpoint.tar.gz. With encryption on, both files are encrypted with the DS's own key.-event-messagesfolder, so a Colab runtime reset lost them. Now the DS restores them from its Drive. When the DS key cannot decrypt the saved state, startup raises and says to log in with thekey_fileof the key that saved it.persist_watcher_statefollowspersist_owner_state, which is off, because an enclave gets a new key at each boot.pre_write_filtercallback that checked the disk. Now thefreeze_private_datasetsconfig flag does this, on by default. It checks the DS's file hashes, and the refused change stays out of the saved state.FileChangeEventrefuses it, and it also refuses content that is not valid base64.Checkpoint.with_events, which the DS's fold uses too.CheckpointFile.contentis now bytes, stored as base64 in JSON, soCHECKPOINT_VERSIONis now 2. A version 1 checkpoint loads with its text as UTF-8 bytes.private/send_queue/folder in the DS's datasite, and a/SyftBox/<email>-<version>-watcher-statefolder on the DS's Drive.client.sync()also uploads saved messages. TheSyftboxManagerConfigbuilders takepersist_watcher_stateandfreeze_private_datasets.on_file_change(process_now=...)andDataSiteWatcherCache.pre_write_filterare gone.Guidelines
High level
freeze_private_datasets.Mid level
Low level
Security
private/send_queue/, until its upload. It is not encrypted there; the upload encrypts it with the DO's key at that time.private/is never synced.Testing
tests/unit/test_send_queue.pycovers:sync()sends after a restart;test_send_before_owner_accepts_goes_once_acceptedreplaces the test that expected the change to be dropped.tests/unit/test_watcher_state.pycovers a restart on an empty folder, a restart after a checkpoint with a deleted file, a new key, watcher state off, the in-memory cache, a binary file, an email in another case, and a change without content.tests/unit/test_watcher_immutable_collections.pycoversfreeze_private_datasetson and off, and a refused change that is not restored after a restart.test_drive_connections.py), encryption at rest (test_encryption.py), checkpoint versions (test_checkpoints.py,test_checkpoint_version.py) and corrupt base64 (test_file_change_events_serialization.py). The integration testtest_ds_cache_aware_sync_gdrivenow restores from Drive.test_all_migratable_objects_in_package_are_registeredfails locally only becauseaiortcis not installed. Integration tests were not run.Asana task