Skip to content

[discussion] MPTT Replacement #12333

Open

Description

@SchrodingersGat

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 and bulk_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 through MPTTModel.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 from get_descendants(), which trusts lft/rght. If run while the interval data is corrupt, promoted children can be missed during tree_id reassignment - 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 / rght means there are no fields to corrupt
  • All calls to rebuild_tree are deleted.
  • bulk_create of 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_id references, ~29 lft/rght references, ~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 the OuterRef('tree_id') subquery annotations in part/filters.py are O(1) indexed filters today and sit under performance-critical list endpoints. CTE equivalents must be benchmarked on large instances; a cheap denormalized root FK (only changes on reparent, none of MPTT's interval arithmetic) may be needed as a substitute
  • Breaking API change. tree_id, level and lft are exposed as serializer fields, filterset fields and ordering fields (e.g. stock/api.py, part/api.py), and documented in api_version.py. tree_depth can replace level; tree_id has no direct equivalent. Requires an API deprecation cycle; third-party plugins may depend on these fields.
  • Library limitations: no .update() on tree querysets, no union() / intersection() / difference(), tree fields are annotations only (not available after refresh_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, OuterRef annotations). Cached pk lists don't compose into querysets - they degrade to pk__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), and MP_Node ships a fix_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_Node have no parent foreign key - structure lives in path strings / intervals, and all mutations must go through its API (add_child(), add_root(), move()) rather than obj.parent = x; obj.save(). InvenTree's models, serializers and public API are built around a parent FK.

External references

django-mptt (upstream acknowledgement of the problem)

django-tree-queries

Related Issues

Activity

  1. added this to the 2.0.0 milestone on Jul 8, 2026
  2. added
    api
    breaking
    migration
    on Jul 8, 2026
  3. changed the title [-]MPTT Replacement[/-] [+][discussion] MPTT Replacement[/+] on Jul 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    apibreakingmigration

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions