BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
1.94k stars 203 forks source link

[BUG] use_revision=True and use_cache=True result in RevisionIdWasChanged error #814

Closed zakajd closed 5 months ago

zakajd commented 7 months ago

Describe the bug For a document with both use_cache and use_revision turned on two consecutive updates result in RevisionIdWasChanged because for the update Beanie always uses a cached document.

To Reproduce

from beanie import Document

class MyDocument(Document):
    field: str = "default value"

    class Config:
        use_cache = True
        cache_capacity = 20
        use_revision = True

async def main():
    # Create and save document
    document = MyDocument(field="initial value")
    await document.save()

    # Get document, update and save
    document = await MyDocument.get(document.id)
    document.field = "updated value"
    await document.save()

    # Update second time
    document = await MyDocument.get(document.id)
    document.field = "updated value 2"
    await document.save() # <- this will fail with RevisionIdWasChanged exception

This is due to the fact, that "update" function internally does a call to "find_one" method with and fetches a stale version of the document.

Expected behavior This edge case should be supported, or at least an "ignore_cache" kwargs should be configurable for the update operation.

zakajd commented 7 months ago

After thinking on this problem a little, I found a solution by running a find_one query with "ignore_cache" flag after each update. This does the Write-through Cache Invalidation, but slightly slows down updates.

roman-right commented 6 months ago

Hi @zakajd , Yes, there is no "smart cache" in Beanie for now. I plan to make interface for cahe soon, so everyone will be able to make custom caching logic. Or even packages with custom cache types. I think, it should help with this.

github-actions[bot] commented 5 months ago

This issue is stale because it has been open 30 days with no activity.

github-actions[bot] commented 5 months ago

This issue was closed because it has been stalled for 14 days with no activity.