Skip to content

RetrieveOrCreateAsync can overwrite a record a concurrent StoreAsync just wrote with new T() (check-then-store race) #144

Closed

Description

@matt-edmondson

What's wrong

Shared/PersistenceDefaults.RetrieveOrCreateAsync (L36-L53), used by FileSystem and Temp, runs in two steps. It first checks for the key with ExistsAsync/RetrieveAsync. If the key looks absent, it then calls StoreAsync(key, new T()) unconditionally. That store goes through AtomicFile.WriteAllTextAsync, which publishes with File.Move(temp, target, overwrite: true) (AtomicFile.cs L125-L126), so it replaces whatever has appeared in the meantime.

The default interface implementation in Essentials/IPersistenceProvider.cs (L54-L76), which ConfigHome, DataHome and InMemory use, has the same check-then-store shape.

Failure scenario

  1. Task A calls RetrieveOrCreateAsync<Settings>("cfg") and finds no file.
  2. Task B calls StoreAsync("cfg", realSettings), which completes.
  3. Task A continues with StoreAsync("cfg", new Settings()), and B's record is replaced by defaults.

#66 listed this data-loss outcome: "RetrieveOrCreateAsync stores a fresh new T() over the real data". #116 closed the delete-then-move window but not this one. A realistic trigger is a startup path that bootstraps settings with RetrieveOrCreateAsync while a migration or import task writes the real record.

InMemory has the same race. There it can also return an instance that is not the one left stored, which is the persistence twin of #85 (the cache provider's GetOrAdd).

Suggested fix

Make the create step create-if-absent:

  • File providers: publish the staged default with a non-overwriting File.Move(temp, target), for example via an AtomicFile.TryCreateAsync. If the target already exists, discard the staged file, then retrieve and return the stored value.
  • InMemory: use an atomic GetOrAdd on the backing dictionary.
  • Tests: race RetrieveOrCreateAsync against StoreAsync of a distinguishable value, and assert the stored value is never replaced by new T() once the store has completed.

Activity

  1. matt-edmondson commented on Oct 18, 2026

    @matt-edmondson
    ContributorAuthor

    Triage


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugSomething isn't working

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions