Skip to content

api: purge reset data in the background - #115

Merged
thecodrr merged 9 commits into
masterfrom
api/background-reset
Oct 30, 2026
Merged

thecodrr merged 9 commits into
masterfrom
api/background-reset

Conversation

@thecodrr

Copy link
Copy Markdown
Contributor

Resetting a large account deleted every sync collection in one Mongo transaction, which outlived Mongo's time limit and the request timeout.

  • Reset: deletes inbox API keys, inbox items, monographs and devices inline. A single settings update then clears the keys, increments Generation and sets PurgePending. Attachments are still deleted from S3 inline and best-effort, since S3 objects carry no generation.
  • Reads: fetches and the encryption verifier only return items from the current generation. Old items, encrypted with the old key, disappear as soon as the request returns. Items without a generation count as 0.
  • Writes: each push stamps its items inside its transaction by incrementing WriteRevision on the user's settings. A reset committed during the push therefore conflicts with it, and the retry gets the new generation.
  • Purge: UserPurgeJob deletes older generations collection by collection. It clears PurgePending only if Generation is unchanged, so a reset made during a purge stays pending and the purge is retried.

Generation logic lives in the new UserGenerations class, 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.

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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment thread Notesnook.API/Services/UserService.cs Resolved
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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved critical races can lose post-reset items or clear new sync state, while cache invalidation gaps can leave revoked tokens usable after reset.

4 open issues
2 resolved since last review

Review effort: Balanced

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);
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.
@thecodrr
thecodrr merged commit 3a05c70 into master Oct 30, 2026
1 check passed
@thecodrr
thecodrr deleted the api/background-reset branch October 30, 2026 07:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants