Repository navigation
api: purge reset data in the background - #115
Merged
Merged
Conversation
Resetting a large account deleted every sync collection in one Mongo transaction, which outlived Mongo's time limit and the request timeout. A reset now deletes the small collections (inbox keys and items, monographs, devices) inline and then, in one settings update, clears the keys, increments the user's Generation and marks a purge as pending. Sync items are stamped with the generation they were pushed in, and fetches and the encryption verifier only see the current one, so the old data disappears as soon as the request returns. UserPurgeJob deletes the older generations one collection at a time and clears the pending mark only if no newer reset happened meanwhile. Each push stamps its items inside its transaction by incrementing the user's WriteRevision, so a reset committed during the push conflicts with it and the retry gets the new generation. Items stored before this change have no generation and count as generation 0.
There was a problem hiding this comment.
🟡 Changes recommended
Critical generation-handling defects can leave lazy-input writes hidden and later purged, or make pre-reset ciphertext visible under a new generation.
3 open issues
What changed in this PR
Moves reset-related sync data deletion to the background, avoiding large MongoDB transactions while using generations to hide old data immediately.
Changes:
- Adds generation-based filtering and transactional stamping of sync items.
- Extends the purge job to delete older generations and preserve pending work across failures or concurrent resets.
- Updates the reset API contract and adds reset, push, and purge integration tests.
| File | Description |
|---|---|
| tests/Notesnook.API.Tests/UserResetTests.cs | Tests reset visibility, concurrent operations, and purge retries. |
| tests/Notesnook.API.Tests/ApiErrorResponseTests.cs | Updates the service constructor call. |
| Notesnook.API/Services/UserService.cs | Advances generations on reset and filters encryption verifiers. |
| Notesnook.API/Services/MongoIndexesHostedService.cs | Adds the pending-purge index. |
| Notesnook.API/Repositories/UserGenerations.cs | Centralizes generation lookup, stamping, and filters. |
| Notesnook.API/Repositories/SyncItemsRepository.cs | Filters reads, stamps writes, and deletes older generations. |
| Notesnook.API/Models/UserSettings.cs | Adds generation, purge status, and write revision fields. |
| Notesnook.API/Models/SyncItem.cs | Adds a server-only generation field. |
| Notesnook.API/Jobs/UserPurgeJob.cs | Processes pending reset purges. |
| Notesnook.API/Interfaces/IUserService.cs | Changes reset to return Task. |
| Notesnook.API/Interfaces/ISyncItemsRepositoryAccessor.cs | Exposes generation support. |
| Notesnook.API/Controllers/UsersController.cs | Adapts the reset endpoint to the service contract. |
| Notesnook.API/Accessors/SyncItemsRepositoryAccessor.cs | Shares generation support across sync repositories. |
Review effort: Balanced
A push retried after a conflicting reset was stamped with the new generation, although its items are still encrypted with the keys the reset cleared. The push now keeps the generation it first saw across retries and is rejected if a reset changed it. Items are stamped through the captured replacements, so a lazily enumerated input isn't left at generation 0. Client errors thrown by a hub method now reach the client as hub errors, since SignalR hides other exceptions' messages outside development.
There was a problem hiding this comment.
🟡 Changes recommended
An already-authenticated inbox request can insert old-key ciphertext after reset, leaving it fetchable because inbox items lack generation filtering and are excluded from the reset purge.
2 open issues
2 resolved since last review
Review effort: Balanced
Sessions are revoked while the user is locked out, retrying and then aborting the reset if that fails. Hub connections, devices, inbox keys and monographs from before a reset are fenced by the user's generation. Identity now calls each server to clear cached tokens instead of publishing a message, and the API and subscription server keep their introspection cache in Redis so every replica sees the clear. Servers without the call still get the message until they're upgraded. Logins during a reset say so, and failed purges are counted for alerting.
- the old devices are purged one at a time in a transaction, so a device registering again keeps the ids recorded for it - the reset purge waits 15 minutes for requests still writing to the old generation, then runs once - republishing a monograph replaces a copy the purge hasn't removed yet - inbox keys from before a reset no longer show or count toward the limit - the reset holds a 10 minute lock through the attachments' removal, refuses to overlap another reset, and keeps a lockout set while it ran - the purge failure counter is exported from the first run
The user's monographs, inbox keys, inbox items and devices are few enough to delete during the reset, before the generation changes, so only the sync items need a generation and a background purge. UserPurgeJob now deletes them itself, and the purge failure counter has no labels.
…nsynced The generation bump, the user check and the deletes of monographs, inbox keys, inbox items and devices run in one transaction, so a failed reset, or one for a user without settings, leaves nothing deleted. A fetch already under way when the reset commits no longer marks its re-registered device as synced, so it still does a full sync after logging in again.
They're told as soon as their sessions end, so their open sync connections close before the reset rather than after it.
Comment on lines
+321
to
+322
| if (await Repositories.Generations.IsCurrentAsync(userId)) | ||
| await SyncDeviceService.ResetAsync(userId, deviceId); |
Comment on lines
+125
to
+127
| var generation = await generations.GetAsync(userId); | ||
| foreach (var write in writes) write.Replacement.Generation = generation; | ||
| await Collection.BulkWriteAsync(handle, writes, options: new BulkWriteOptions { IsOrdered = false }, ct); |
| : await sessionStore.EndSessionsAsync(client.Id, user.Id.ToString(), jti, refreshToken); | ||
|
|
||
| await PublishClearCacheAsync(removedKeys); | ||
| await ClearCacheAsync(removedKeys); |
Comment on lines
+201
to
+202
| var cache = await server.GetServiceAsync<ITokenCacheService>().WaitAsync(ClearCacheTimeout); | ||
| await cache.ClearAsync([.. keys]).WaitAsync(ClearCacheTimeout); |
…sessions weren't ended
Ending sessions deletes them before their cached tokens are cleared, so a retry after a failed clear found nothing to clear and succeeded while the revoked tokens still worked from the cache.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Resetting a large account deleted every sync collection in one Mongo transaction, which outlived Mongo's time limit and the request timeout.
Generationand setsPurgePending. Attachments are still deleted from S3 inline and best-effort, since S3 objects carry no generation.WriteRevisionon the user's settings. A reset committed during the push therefore conflicts with it, and the retry gets the new generation.UserPurgeJobdeletes older generations collection by collection. It clearsPurgePendingonly ifGenerationis unchanged, so a reset made during a purge stays pending and the purge is retried.Generation logic lives in the new
UserGenerationsclass, so the repository method signatures are unchanged.Every push now writes the user's settings document, so concurrent pushes from the same user conflict on it and retry.
Tests cover: old items hidden from fetch and the verifier right after a reset, pushes after a reset surviving the purge, a push overlapping a reset being retried with the new generation, a reset during a purge staying pending, and a failed purge being retried.