Description
On the anniversary of our previous major tree structure change:
Concurrency Issues with MPTT
Background
InvenTree uses django-mptt to manage tree structures for five models:
| Model | Tree relationship |
|---|---|
PartCategory |
Category hierarchy |
Part |
Variant hierarchy (variant_of) |
StockLocation |
Location hierarchy |
StockItem |
Stock item ancestry (splits / serialization) |
Build |
Parent / child build orders |
MPTT stores pre-computed tree_id / lft / rght / level values on every row. This makes subtree reads cheap, but every insert, move or delete must update many sibling / ancestor rows, which can prove expensive when updating a large number of items.
Additionally, the added row values can become inconsistent under concurrent writes. In production this manifests as recurring errors such as:
More than one root node with tree_id 32034. That's invalid, do a full rebuild.
raised from rebuild_stock_item_tree and StockItem.partial_rebuild - typically observed when consuming stock against large build orders while multiple users are active. The error occurs when a tree rebuild discovers that two root nodes (parent = None) share the same tree_id. The duplicate roots are created earlier, by unrelated concurrent operations (see bugs below), and every subsequent operation on the poisoned tree_id then fails until a full tree rebuild runs.
Example Error Log
Traceback (most recent call last):
File "/opt/inventree/src/backend/InvenTree/InvenTree/models.py", line 958, in partial_rebuild
self.__class__.objects.partial_rebuild(tree_id)
File "/opt/inventree/.venv/lib/python3.12/site-packages/mptt/managers.py", line 46, in wrapped
return method(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/inventree/.venv/lib/python3.12/site-packages/mptt/managers.py", line 716, in partial_rebuild
raise RuntimeError(
RuntimeError: More than one root node with tree_id 32034. That's invalid, do a full rebuild.django-mptt is unmaintained
The django-mptt project explicitly declares itself unmaintained, and its README acknowledges this exact failure class:
"every insert, move, or delete must update a potentially large number of sibling and ancestor rows. This write amplification is the fundamental reason the library is hard to maintain: concurrent writes can race and corrupt the tree, bulk operations bypass the update logic entirely, and any code that touches the database outside of django-mptt (raw SQL,
bulk_update, migrations) can leave the tree in an inconsistent state."
Bugs / weak spots identified in the current codebase
1. Racy tree_id allocation (MAX + 1, no locking)
Every tree_id allocator in the codebase (and inside django-mptt itself) is an unlocked read-then-write of SELECT MAX(tree_id) + 1:
InvenTreeTree.getNextTreeID()(src/backend/InvenTree/InvenTree/models.py, ~L1006) - used when saving new root nodes and when reassigning subtrees during root deletion.StockItem._create_serial_numbers()(src/backend/InvenTree/stock/models.py, ~L712) - allocates an entire range of tree_ids in Python andbulk_creates root nodes into them. Called from three concurrent-user hot paths: build output creation (build/models.py~L873), PO receipt of serialized stock (order/models.py~L1199), and the stock serialization API (stock/api.py~L1259).- django-mptt's own
TreeManager._get_next_tree_id()- same pattern, hit on any root insert that goes throughMPTTModel.save().
Two concurrent transactions read the same MAX, both insert root nodes at the same tree_id, and both commit cleanly. Two users simultaneously creating serialized build outputs / receiving purchase orders can corrupt dozens of tree_ids in a single race.
2. Concurrent MPTT writes corrupt lft / rght
Concurrent child inserts into the same tree (e.g. two users splitting stock from the same tree) interleave MPTT's space-making SQL, producing invalid interval values. The follow-up partial_rebuild normally heals this (it derives structure from parent links), but:
- Two concurrent rebuilds of the same tree interleave their bulk updates and leave garbage.
InvenTreeTree.delete()computes subtree membership fromget_descendants(), which trustslft/rght. If run while the interval data is corrupt, promoted children can be missed duringtree_idreassignment - converting transient interval noise into a persistent duplicate root.
3. The recovery path can re-corrupt data
On partial rebuild failure, a full StockItem.objects.rebuild() is offloaded to the background worker while web workers continue mutating stock. rebuild() renumbers all tree_ids and is itself unsafe against concurrent inserts.
4. No database-level guard
There is no constraint preventing two root nodes from sharing a tree_id (a partial unique index UNIQUE (tree_id) WHERE parent_id IS NULL on PostgreSQL / SQLite; requires a generated-column workaround on MySQL, which lacks partial indexes). Duplicates are only ever detected, later, by a failing rebuild in some unrelated user's request.
Option: migrate to django-tree-queries
django-tree-queries stores only the parent foreign key. Tree fields (tree_depth, tree_path, tree_ordering) are computed at query time via recursive CTEs (with_tree_fields()), with tree_filter() / tree_exclude() to constrain the CTE for performance. It is actively maintained, and is the successor recommended by django-mptt's own README.
Pros
- Eliminates the entire corruption class. No stored
tree_id/lft/rghtmeans there are no fields to corrupt - All calls to
rebuild_treeare deleted. bulk_createof tree rows becomes safe and simple- Actively maintained dependency; removes a permanently-unmaintained one.
- Supported on all our database backends: PostgreSQL, SQLite 3.8.3+, MariaDB 10.2.2+, MySQL 8.0+.
Cons / architectural changes required
- Query pattern rewrite. Current backend usage (excluding tests/migrations): ~90
tree_idreferences, ~29lft/rghtreferences, ~101 traversal calls (get_descendants/get_ancestors/get_children). - Performance risk . Patterns like
part__tree_id=X(variant family),location__tree_id=Y(location subtree), and theOuterRef('tree_id')subquery annotations inpart/filters.pyare O(1) indexed filters today and sit under performance-critical list endpoints. CTE equivalents must be benchmarked on large instances; a cheap denormalizedrootFK (only changes on reparent, none of MPTT's interval arithmetic) may be needed as a substitute - Breaking API change.
tree_id,levelandlftare exposed as serializer fields, filterset fields and ordering fields (e.g.stock/api.py,part/api.py), and documented inapi_version.py.tree_depthcan replacelevel;tree_idhas no direct equivalent. Requires an API deprecation cycle; third-party plugins may depend on these fields. - Library limitations: no
.update()on tree querysets, nounion()/intersection()/difference(), tree fields are annotations only (not available afterrefresh_from_db()), - max 50 tree levels on MySQL/MariaDB
- Migration effort spans five models and a schema migration each
Alternatives considered (and why not)
The corruption class described above is not a django-mptt bug per se - it is inherent to any design that stores derived tree state on rows and updates it with unserialized read-then-write operations. That rules out most of the alternatives:
django-treenode - no
django-treenode is actively maintained, but swaps MPTT's interval fields for even heavier denormalization: per-row serialized pk lists (tn_ancestors_pks, tn_descendants_pks, tn_children_pks, plus depth/order fields), recomputed via signal-triggered update_tree() on every structural change.
- Same race class as MPTT: derived state is recomputed in Python from a snapshot and bulk-written back with no locking. Two concurrent writers recompute from different snapshots; last writer wins. The documentation makes no statement about concurrency, atomicity or thread safety.
- Worse write amplification at our scale: pk-list fields are rewritten across the tree on every change (the docs recommend disabling signals for bulk operations because the per-save cost is so high). Descendant pk lists on large tables become large text blobs rewritten constantly.
- Multi-process cache staleness: the "synced in-memory instances" feature rides on the Django cache framework. InvenTree runs multi-process (gunicorn workers + background worker), so instance navigation can silently return stale trees - a new bug class MPTT doesn't have.
- Poor queryset composition: our hot idioms are relational subtree filters (
location__tree_id=X,OuterRefannotations). Cached pk lists don't compose into querysets - they degrade topk__in=<huge list>or string matching on serialized fields.
django-treebeard - no
django-treebeard is actively maintained (it underpins Wagtail) and is honest about this problem - which is itself instructive:
- Its Known Caveats page acknowledges race conditions directly: operations are wrapped in transactions "to minimise the impact of race conditions, but it is still possible for data to end up in an inconsistent state" under concurrent writes, and suggests projects "apply additional locks (e.g. lock the whole table when performing a move)".
- Row locks for concurrent
add_child()/ root creation were only added in 5.0.3 (#53), andMP_Nodeships afix_tree()recovery method - the existence of which tells you corruption is an expected operational event, exactly like our rebuild tasks today. - All three of its strategies store derived state (materialized paths, nested-set intervals, or sibling order). Migrating would trade our current corruption modes for treebeard's, plus its documented table-locking mitigation - which we could apply to MPTT with less effort.
- Architecturally it is the most invasive option:
MP_Node/NS_Nodehave noparentforeign key - structure lives in path strings / intervals, and all mutations must go through its API (add_child(),add_root(),move()) rather thanobj.parent = x; obj.save(). InvenTree's models, serializers and public API are built around aparentFK.
External references
django-mptt (upstream acknowledgement of the problem)
- django-mptt README - "This project is currently unmaintained"; "concurrent writes can race and corrupt the tree".
- django-mptt#236 - Tree gets corrupted when concurrently adding multiple root objects - concurrent root creation obtains the same
tree_idvia_get_next_tree_id(); closed without a fix. - django-mptt#555 - Concurrency and pre-calculated tree_id - the delay between computing and writing the tree_id lets two trees share an ID.
- django-mptt#687 - MPTTModel.save() assigns duplicate tree_id's - duplicate root tree_ids via the
order_insertion_bypath; reporter's workaround was removingorder_insertion_by. - django-mptt#677 - root_node_ordering flag PR - attempted opt-out of root-ordering / tree shifts for concurrency and performance reasons; never merged.
- django-mptt documentation - note: contains no concurrency guidance at all.
django-tree-queries
- django-tree-queries repository
- Announcement blog post - "Tree queries in Django" - design rationale for CTE-based trees vs. stored tree state.
- django-tree-queries#38 - Concurrency concerns - discussion of the (much smaller) residual concurrency surface of the CTE approach.
Activity
[-]MPTT Replacement[/-][+][discussion] MPTT Replacement[/+]