We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
IntegrityError: (1062, "Duplicate entry 'xxx-stats' for key > 'pootle_revision_content_type_id_xxx_uniq'")
This error has been spotted in the wild.

From code review its hard to see how its happening, and i ~~havent~~ managed to reproduce - *by clicking very fast on editor buttons*

~~It may be related to update_stores~~

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pootle/apps/pootle_revision/utils.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) Pootle contributors.
4 #
5 # This file is a part of the Pootle project. It is distributed under the GPL3
6 # or later license. See the LICENSE file for a copy of the license and the
7 # AUTHORS file for copyright and authorship information.
8 
9 import uuid
10 
11 from django.contrib.contenttypes.models import ContentType
12 from django.utils.functional import cached_property
13 
14 from pootle.core.url_helpers import split_pootle_path
15 from pootle_app.models import Directory
16 
17 from .models import Revision
18 
19 
20 class RevisionContext(object):
21 
22     def __init__(self, context):
23         self.context = context
24 
25     @cached_property
26     def content_type_id(self):
27         return ContentType.objects.get_for_model(
28             self.context._meta.model).id
29 
30     @property
31     def revision_context(self):
32         return self.context.revisions
33 
34     def get(self, key=None):
35         """get a revision from db or set one if not set"""
36         if not self.revision_context:
37             return ""
38         return self.revision_context.filter(
39             key=key).values_list("value", flat=True).first() or ""
40 
41     def set(self, keys=None, value=None):
42         """get a revision from db or set one if not set"""
43         self.revision_context.filter(key__in=keys).delete()
44         if value:
45             revisions = []
46             for k in keys:
47                 revisions.append(
48                     Revision(
49                         content_type_id=self.content_type_id,
50                         object_id=self.context.pk,
51                         key=k,
52                         value=value))
53             Revision.objects.bulk_create(revisions)
54 
55 
56 class DirectoryRevision(RevisionContext):
57     pass
58 
59 
60 class LanguageRevision(RevisionContext):
61 
62     @property
63     def revision_context(self):
64         return self.context.directory.revisions
65 
66 
67 class ProjectRevision(RevisionContext):
68     pass
69 
70 
71 class ProjectResourceRevision(RevisionContext):
72 
73     @property
74     def revision_context(self):
75         first_child = self.context.children.first()
76         if not first_child:
77             return
78         return Directory.objects.get(
79             pootle_path="/projects/%s/"
80             % split_pootle_path(first_child.pootle_path)[1]).revisions
81 
82 
83 class ProjectSetRevision(RevisionContext):
84 
85     @property
86     def revision_context(self):
87         first_project = self.context.children.first()
88         if not first_project:
89             return
90         return first_project.directory.parent.revisions
91 
92 
93 class TPRevision(RevisionContext):
94     pass
95 
96 
97 class RevisionUpdater(object):
98 
99     def __init__(self, context=None, object_list=None):
100         self.context = context
101         self.object_list = object_list
102 
103     @property
104     def object_list_paths(self):
105         return set(
106             self.object_list.values_list(
107                 self.related_pootle_path,
108                 flat=True))
109 
110     @property
111     def all_pootle_paths(self):
112         if self.context and not self.object_list:
113             return set([self.context_path])
114         elif self.object_list:
115             parents = self.object_list_paths
116             if self.context:
117                 parents.add(self.context_path)
118             return parents
119         return []
120 
121     @property
122     def parents(self):
123         """calculate unit parents for cache update"""
124         return Directory.objects.filter(
125             pootle_path__in=self.get_parent_paths(self.all_pootle_paths))
126 
127     def get_parent_paths(self, pootle_paths):
128         paths = set(["/projects/"])
129         for pootle_path in pootle_paths:
130             lang_code, proj_code, dir_path, __ = split_pootle_path(pootle_path)
131             paths.add("/projects/%s/" % proj_code)
132             paths.add("/%s/" % lang_code)
133             paths.add("/%s/%s/" % (lang_code, proj_code))
134             dir_path_parts = dir_path.split("/")
135             for i, name in enumerate(dir_path_parts):
136                 if not name:
137                     continue
138                 paths.add(
139                     "/%s/%s/%s/"
140                     % (lang_code,
141                        proj_code,
142                        "/".join(dir_path_parts[:i + 1])))
143         return paths
144 
145     @property
146     def new_revision(self):
147         return uuid.uuid4().hex
148 
149     @cached_property
150     def content_type_id(self):
151         return ContentType.objects.get_for_model(Directory).id
152 
153     def get_revisions(self, parents, keys=None):
154         return Revision.objects.filter(
155             content_type_id=self.content_type_id,
156             key__in=keys or [""],
157             object_id__in=parents)
158 
159     def create_revisions(self, parents, keys=None):
160         new_revision = self.new_revision
161         for parent in parents:
162             for key in keys or [""]:
163                 yield Revision(
164                     content_type_id=self.content_type_id,
165                     object_id=parent,
166                     key=key,
167                     value=new_revision)
168 
169     def update(self, keys=None):
170         parents = list(self.parents.values_list("id", flat=True))
171         revisions = self.get_revisions(parents, keys=keys)
172         revisions.delete()
173         Revision.objects.bulk_create(
174             self.create_revisions(parents, keys=keys))
175 
176 
177 class UnitRevisionUpdater(RevisionUpdater):
178     related_pootle_path = "store__parent__pootle_path"
179 
180     @property
181     def context_path(self):
182         return self.context.store.parent.pootle_path
183 
184 
185 class StoreRevisionUpdater(RevisionUpdater):
186     related_pootle_path = "parent__pootle_path"
187 
188     @property
189     def context_path(self):
190         return self.context.parent.pootle_path
191 
192 
193 class DirectoryRevisionUpdater(RevisionUpdater):
194     related_pootle_path = "pootle_path"
195 
196     @property
197     def context_path(self):
198         return self.context.pootle_path
199
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pootle/apps/pootle_revision/utils.py b/pootle/apps/pootle_revision/utils.py
--- a/pootle/apps/pootle_revision/utils.py
+++ b/pootle/apps/pootle_revision/utils.py
@@ -169,7 +169,10 @@
     def update(self, keys=None):
         parents = list(self.parents.values_list("id", flat=True))
         revisions = self.get_revisions(parents, keys=keys)
-        revisions.delete()
+        # manually get the list of ids and delete those to prevent
+        # django race condition
+        revision_ids = list(revisions.values_list("id", flat=True))
+        revisions.filter(id__in=revision_ids).delete()
         Revision.objects.bulk_create(
             self.create_revisions(parents, keys=keys))

{"golden_diff": "diff --git a/pootle/apps/pootle_revision/utils.py b/pootle/apps/pootle_revision/utils.py\n--- a/pootle/apps/pootle_revision/utils.py\n+++ b/pootle/apps/pootle_revision/utils.py\n@@ -169,7 +169,10 @@\n     def update(self, keys=None):\n         parents = list(self.parents.values_list(\"id\", flat=True))\n         revisions = self.get_revisions(parents, keys=keys)\n-        revisions.delete()\n+        # manually get the list of ids and delete those to prevent\n+        # django race condition\n+        revision_ids = list(revisions.values_list(\"id\", flat=True))\n+        revisions.filter(id__in=revision_ids).delete()\n         Revision.objects.bulk_create(\n             self.create_revisions(parents, keys=keys))\n", "issue": "IntegrityError: (1062, \"Duplicate entry 'xxx-stats' for key > 'pootle_revision_content_type_id_xxx_uniq'\")\nThis error has been spotted in the wild.\r\n\r\nFrom code review its hard to see how its happening, and i ~~havent~~ managed to reproduce - *by clicking very fast on editor buttons*\r\n\r\n~~It may be related to update_stores~~\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport uuid\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.utils.functional import cached_property\n\nfrom pootle.core.url_helpers import split_pootle_path\nfrom pootle_app.models import Directory\n\nfrom .models import Revision\n\n\nclass RevisionContext(object):\n\n    def __init__(self, context):\n        self.context = context\n\n    @cached_property\n    def content_type_id(self):\n        return ContentType.objects.get_for_model(\n            self.context._meta.model).id\n\n    @property\n    def revision_context(self):\n        return self.context.revisions\n\n    def get(self, key=None):\n        \"\"\"get a revision from db or set one if not set\"\"\"\n        if not self.revision_context:\n            return \"\"\n        return self.revision_context.filter(\n            key=key).values_list(\"value\", flat=True).first() or \"\"\n\n    def set(self, keys=None, value=None):\n        \"\"\"get a revision from db or set one if not set\"\"\"\n        self.revision_context.filter(key__in=keys).delete()\n        if value:\n            revisions = []\n            for k in keys:\n                revisions.append(\n                    Revision(\n                        content_type_id=self.content_type_id,\n                        object_id=self.context.pk,\n                        key=k,\n                        value=value))\n            Revision.objects.bulk_create(revisions)\n\n\nclass DirectoryRevision(RevisionContext):\n    pass\n\n\nclass LanguageRevision(RevisionContext):\n\n    @property\n    def revision_context(self):\n        return self.context.directory.revisions\n\n\nclass ProjectRevision(RevisionContext):\n    pass\n\n\nclass ProjectResourceRevision(RevisionContext):\n\n    @property\n    def revision_context(self):\n        first_child = self.context.children.first()\n        if not first_child:\n            return\n        return Directory.objects.get(\n            pootle_path=\"/projects/%s/\"\n            % split_pootle_path(first_child.pootle_path)[1]).revisions\n\n\nclass ProjectSetRevision(RevisionContext):\n\n    @property\n    def revision_context(self):\n        first_project = self.context.children.first()\n        if not first_project:\n            return\n        return first_project.directory.parent.revisions\n\n\nclass TPRevision(RevisionContext):\n    pass\n\n\nclass RevisionUpdater(object):\n\n    def __init__(self, context=None, object_list=None):\n        self.context = context\n        self.object_list = object_list\n\n    @property\n    def object_list_paths(self):\n        return set(\n            self.object_list.values_list(\n                self.related_pootle_path,\n                flat=True))\n\n    @property\n    def all_pootle_paths(self):\n        if self.context and not self.object_list:\n            return set([self.context_path])\n        elif self.object_list:\n            parents = self.object_list_paths\n            if self.context:\n                parents.add(self.context_path)\n            return parents\n        return []\n\n    @property\n    def parents(self):\n        \"\"\"calculate unit parents for cache update\"\"\"\n        return Directory.objects.filter(\n            pootle_path__in=self.get_parent_paths(self.all_pootle_paths))\n\n    def get_parent_paths(self, pootle_paths):\n        paths = set([\"/projects/\"])\n        for pootle_path in pootle_paths:\n            lang_code, proj_code, dir_path, __ = split_pootle_path(pootle_path)\n            paths.add(\"/projects/%s/\" % proj_code)\n            paths.add(\"/%s/\" % lang_code)\n            paths.add(\"/%s/%s/\" % (lang_code, proj_code))\n            dir_path_parts = dir_path.split(\"/\")\n            for i, name in enumerate(dir_path_parts):\n                if not name:\n                    continue\n                paths.add(\n                    \"/%s/%s/%s/\"\n                    % (lang_code,\n                       proj_code,\n                       \"/\".join(dir_path_parts[:i + 1])))\n        return paths\n\n    @property\n    def new_revision(self):\n        return uuid.uuid4().hex\n\n    @cached_property\n    def content_type_id(self):\n        return ContentType.objects.get_for_model(Directory).id\n\n    def get_revisions(self, parents, keys=None):\n        return Revision.objects.filter(\n            content_type_id=self.content_type_id,\n            key__in=keys or [\"\"],\n            object_id__in=parents)\n\n    def create_revisions(self, parents, keys=None):\n        new_revision = self.new_revision\n        for parent in parents:\n            for key in keys or [\"\"]:\n                yield Revision(\n                    content_type_id=self.content_type_id,\n                    object_id=parent,\n                    key=key,\n                    value=new_revision)\n\n    def update(self, keys=None):\n        parents = list(self.parents.values_list(\"id\", flat=True))\n        revisions = self.get_revisions(parents, keys=keys)\n        revisions.delete()\n        Revision.objects.bulk_create(\n            self.create_revisions(parents, keys=keys))\n\n\nclass UnitRevisionUpdater(RevisionUpdater):\n    related_pootle_path = \"store__parent__pootle_path\"\n\n    @property\n    def context_path(self):\n        return self.context.store.parent.pootle_path\n\n\nclass StoreRevisionUpdater(RevisionUpdater):\n    related_pootle_path = \"parent__pootle_path\"\n\n    @property\n    def context_path(self):\n        return self.context.parent.pootle_path\n\n\nclass DirectoryRevisionUpdater(RevisionUpdater):\n    related_pootle_path = \"pootle_path\"\n\n    @property\n    def context_path(self):\n        return self.context.pootle_path\n", "path": "pootle/apps/pootle_revision/utils.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport uuid\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.utils.functional import cached_property\n\nfrom pootle.core.url_helpers import split_pootle_path\nfrom pootle_app.models import Directory\n\nfrom .models import Revision\n\n\nclass RevisionContext(object):\n\n    def __init__(self, context):\n        self.context = context\n\n    @cached_property\n    def content_type_id(self):\n        return ContentType.objects.get_for_model(\n            self.context._meta.model).id\n\n    @property\n    def revision_context(self):\n        return self.context.revisions\n\n    def get(self, key=None):\n        \"\"\"get a revision from db or set one if not set\"\"\"\n        if not self.revision_context:\n            return \"\"\n        return self.revision_context.filter(\n            key=key).values_list(\"value\", flat=True).first() or \"\"\n\n    def set(self, keys=None, value=None):\n        \"\"\"get a revision from db or set one if not set\"\"\"\n        self.revision_context.filter(key__in=keys).delete()\n        if value:\n            revisions = []\n            for k in keys:\n                revisions.append(\n                    Revision(\n                        content_type_id=self.content_type_id,\n                        object_id=self.context.pk,\n                        key=k,\n                        value=value))\n            Revision.objects.bulk_create(revisions)\n\n\nclass DirectoryRevision(RevisionContext):\n    pass\n\n\nclass LanguageRevision(RevisionContext):\n\n    @property\n    def revision_context(self):\n        return self.context.directory.revisions\n\n\nclass ProjectRevision(RevisionContext):\n    pass\n\n\nclass ProjectResourceRevision(RevisionContext):\n\n    @property\n    def revision_context(self):\n        first_child = self.context.children.first()\n        if not first_child:\n            return\n        return Directory.objects.get(\n            pootle_path=\"/projects/%s/\"\n            % split_pootle_path(first_child.pootle_path)[1]).revisions\n\n\nclass ProjectSetRevision(RevisionContext):\n\n    @property\n    def revision_context(self):\n        first_project = self.context.children.first()\n        if not first_project:\n            return\n        return first_project.directory.parent.revisions\n\n\nclass TPRevision(RevisionContext):\n    pass\n\n\nclass RevisionUpdater(object):\n\n    def __init__(self, context=None, object_list=None):\n        self.context = context\n        self.object_list = object_list\n\n    @property\n    def object_list_paths(self):\n        return set(\n            self.object_list.values_list(\n                self.related_pootle_path,\n                flat=True))\n\n    @property\n    def all_pootle_paths(self):\n        if self.context and not self.object_list:\n            return set([self.context_path])\n        elif self.object_list:\n            parents = self.object_list_paths\n            if self.context:\n                parents.add(self.context_path)\n            return parents\n        return []\n\n    @property\n    def parents(self):\n        \"\"\"calculate unit parents for cache update\"\"\"\n        return Directory.objects.filter(\n            pootle_path__in=self.get_parent_paths(self.all_pootle_paths))\n\n    def get_parent_paths(self, pootle_paths):\n        paths = set([\"/projects/\"])\n        for pootle_path in pootle_paths:\n            lang_code, proj_code, dir_path, __ = split_pootle_path(pootle_path)\n            paths.add(\"/projects/%s/\" % proj_code)\n            paths.add(\"/%s/\" % lang_code)\n            paths.add(\"/%s/%s/\" % (lang_code, proj_code))\n            dir_path_parts = dir_path.split(\"/\")\n            for i, name in enumerate(dir_path_parts):\n                if not name:\n                    continue\n                paths.add(\n                    \"/%s/%s/%s/\"\n                    % (lang_code,\n                       proj_code,\n                       \"/\".join(dir_path_parts[:i + 1])))\n        return paths\n\n    @property\n    def new_revision(self):\n        return uuid.uuid4().hex\n\n    @cached_property\n    def content_type_id(self):\n        return ContentType.objects.get_for_model(Directory).id\n\n    def get_revisions(self, parents, keys=None):\n        return Revision.objects.filter(\n            content_type_id=self.content_type_id,\n            key__in=keys or [\"\"],\n            object_id__in=parents)\n\n    def create_revisions(self, parents, keys=None):\n        new_revision = self.new_revision\n        for parent in parents:\n            for key in keys or [\"\"]:\n                yield Revision(\n                    content_type_id=self.content_type_id,\n                    object_id=parent,\n                    key=key,\n                    value=new_revision)\n\n    def update(self, keys=None):\n        parents = list(self.parents.values_list(\"id\", flat=True))\n        revisions = self.get_revisions(parents, keys=keys)\n        # manually get the list of ids and delete those to prevent\n        # django race condition\n        revision_ids = list(revisions.values_list(\"id\", flat=True))\n        revisions.filter(id__in=revision_ids).delete()\n        Revision.objects.bulk_create(\n            self.create_revisions(parents, keys=keys))\n\n\nclass UnitRevisionUpdater(RevisionUpdater):\n    related_pootle_path = \"store__parent__pootle_path\"\n\n    @property\n    def context_path(self):\n        return self.context.store.parent.pootle_path\n\n\nclass StoreRevisionUpdater(RevisionUpdater):\n    related_pootle_path = \"parent__pootle_path\"\n\n    @property\n    def context_path(self):\n        return self.context.parent.pootle_path\n\n\nclass DirectoryRevisionUpdater(RevisionUpdater):\n    related_pootle_path = \"pootle_path\"\n\n    @property\n    def context_path(self):\n        return self.context.pootle_path\n", "path": "pootle/apps/pootle_revision/utils.py"}]}