Skip to content

[Bug] Dataset cleanup performs quadratic ORM work and holds long write transactions #44358

Closed

Description

@zhaohao1004

Self Checks

  • I have read the Contributing Guide and Language Policy.
  • This is only for bug report, if you would like to ask a question, please head to Discussions.
  • I have searched for existing issues search for existing issues, including closed ones.
  • I confirm that I am using English to submit this report, otherwise it will be closed.
  • 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
  • Please do not modify this template :) and fill in all the required fields.

Dify version

Observed in a 1.17.1-based production deployment. The same cleanup loop is still present in freshly fetched main at 08d3c547ecb6e2d8ae6a26a2869e2a93d112f4ec (2026-10-19), whose lockfile also pins SQLAlchemy 2.0.49.

Latest-main verification consists of source comparison and an isolated same-version ORM reproduction; I have not replayed the full incident end-to-end on a main deployment.

Cloud or Self Hosted

Cloud

Steps to reproduce

  1. Create a knowledge base with many text-only document segments, without embedded uploaded-image references. The relevant loop does not require concurrent indexing.
  2. Delete the knowledge base, which dispatches tasks.clean_dataset_task.clean_dataset_task.
  3. Observe the cleanup worker's SQL and PostgreSQL transaction age. Each segment still issues an UploadFile SELECT and DELETE even though the image ID list is empty. The segment loop has no intermediate commit.
  4. Use the isolated reproduction below to verify SQL counts and ORM state enumeration without Dify services or a production database.
Standalone reproduction: Python 3.13 + SQLAlchemy 2.0.49 + SQLite in memory

Save as repro.py and run uv run --python 3.13 --with sqlalchemy==2.0.49 repro.py.

import json
import sqlalchemy as sa
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from sqlalchemy.orm.identity import WeakInstanceDict

class Base(DeclarativeBase):
    pass

class Segment(Base):
    __tablename__ = "segments"
    id: Mapped[int] = mapped_column(primary_key=True)

class UploadFile(Base):
    __tablename__ = "upload_files"
    id: Mapped[int] = mapped_column(primary_key=True)

# Count identity-map enumeration without changing which states are returned.
class CountingMap(WeakInstanceDict):
    scans = 0
    visits = 0

    def all_states(self):
        states = super().all_states()
        self.scans += 1
        self.visits += len(states)
        return states

def reproduce(n, synchronize_session="auto"):
    engine = sa.create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
    with engine.begin() as connection:
        connection.execute(sa.insert(Segment), [{"id": i} for i in range(n)])
    statements = []
    def record(connection, cursor, statement, parameters, context, executemany):
        statements.append(statement.split()[0])
    with Session(engine) as session:
        session.identity_map = CountingMap()
        segments = session.scalars(sa.select(Segment)).all()  # Keep strong refs.
        sa.event.listen(engine, "before_cursor_execute", record)
        for segment in segments:
            image_ids = []  # A segment with no embedded uploaded images.
            session.scalars(sa.select(UploadFile).where(UploadFile.id.in_(image_ids))).all()
            session.execute(
                sa.delete(UploadFile).where(UploadFile.id.in_(image_ids)),
                execution_options={"synchronize_session": synchronize_session},
            )
        sa.event.remove(engine, "before_cursor_execute", record)
        result = dict(n=n, sync=synchronize_session, sql=len(statements),
                      selects=statements.count("SELECT"), deletes=statements.count("DELETE"),
                      scans=session.identity_map.scans, visits=session.identity_map.visits,
                      transaction_open=session.in_transaction())
        assert result["sql"] == 2 * n
        assert result["visits"] == (n * n if synchronize_session == "auto" else 0)
    engine.dispose()
    return result

print(json.dumps({"sqlalchemy": sa.__version__}))
for n, sync in [(500, "auto"), (1000, "auto"), (1000, False)]:
    print(json.dumps(reproduce(n, sync)))

Verified output, with nonessential fields omitted:

N=500,  sync=auto:  1,000 SQL statements,   250,000 identity-state visits
N=1000, sync=auto:  2,000 SQL statements, 1,000,000 identity-state visits
N=1000, sync=False: 2,000 SQL statements,         0 identity-state visits
transaction_open=True in all three cases

This reproduces the ORM loop mechanism. It does not simulate PostgreSQL MVCC/vacuum or reproduce the full production task duration.

✔️ Expected Behavior

Dataset cleanup should have bounded memory usage and transaction duration. Segments without uploaded images should not issue image SELECT/DELETE statements. Work should scale with the amount of data being removed, without repeatedly scanning every retained ORM object for each segment.

Partial progress, file/vector side effects, and retries should remain safe and idempotent when cleanup is batched.

❌ Actual Behavior

The segment loop produces 2N SQL statements and a quadratic in-memory synchronization component while retaining a write transaction.

Current-main code:

  • Lines 70-71 load all documents and segments with .all() into one Session. The segments list retains the ORM objects throughout the loop.
  • Lines 115-116 mark documents for deletion. The subsequent query can autoflush these deletes, so the transaction has already performed writes before segment cleanup completes.
  • Lines 119-136 perform the UploadFile SELECT and ORM DELETE for every segment without checking whether image_upload_file_ids is empty. The loop also performs external storage deletions when files exist.
  • Line 194 commits only after the segment loop and the remaining cleanup work. No commit occurs inside the segment loop.
  • Session factory uses ordinary Session defaults, and the lockfile pins SQLAlchemy 2.0.49.

For an empty image list, PostgreSQL receives this zero-match statement:

DELETE FROM upload_files WHERE upload_files.id IN (NULL) AND (1 != 1)

In the installed SQLAlchemy 2.0.49 implementation, default synchronize_session="auto" selects evaluate for this criterion. BulkORMDelete._do_post_synchronize_evaluate() calls session.identity_map.all_states(), then filters states by mapper. Thus, DocumentSegment objects are still visited even though the DELETE targets UploadFile. With N retained segments and N deletes, this creates an O(N × M) state-inspection component, where M includes those N segments: O(N²). The SQL statement count itself is linear, 2N.

The deployed loop and the latest-main loop are AST-identical. This is not removed by the newer crawl-cache cleanup that runs before the Session is opened.

Observed operational impact, with resource/customer identifiers omitted:

  • A cleanup task and its write transaction remained active for more than 15 hours. Vector cleanup had already completed; the task stayed in the subsequent document/file cleanup phase.
  • Repeated PostgreSQL samples showed the same transaction and advancing query_start, with the empty DELETE above as the latest statement and idle in transaction / ClientRead between statements.
  • The old transaction ID matched the autovacuum removal horizon. Millions of dead tuples in a large table and its TOAST table in the same database could not be reclaimed; repeated autovacuum scans coincided with sustained high read IOPS.
  • The worker consumed about one CPU core. We have not profiled the full task, so do not attribute all of its elapsed time to ORM synchronization; SQL round trips, content scanning, and any storage operations can also contribute.

Fix considerations: skipping empty image IDs removes the no-op path, but a complete fix also needs bounded segment batches and transaction boundaries. Disabling Session synchronization alone only removes the identity-map scan; it leaves the per-segment SQL, full .all(), and long transaction. Any change to synchronization must account for ORM objects used later in the task.

Related work: #38518 already reports full-table loading / all-or-nothing cleanup in the indexing-deletion race scenario. Open, unmerged PR #38519 introduces committed steps and bounded batches, including an empty-file-ID guard. This report adds an independently reproduced empty-delete / quadratic ORM mechanism and the PostgreSQL vacuum impact; it does not claim those earlier reports or proposed fixes do not exist.

Activity

  1. added
    🐞 bug
    on Oct 19, 2026
  2. dosubot commented on Oct 19, 2026

    @dosubot

    There is a useful implementation reference in batch_clean_document_task: it guards empty image/file ID lists, deletes image rows and segments in batches of 1,000 with a fresh session and commit per batch, and performs storage deletion outside those database transactions. Those patterns are relevant to the transaction-duration part of this report. [1]

    It is not a complete bounded-memory template, though: that task still loads all matching segments with .all() and accumulates IDs and storage keys upfront. Dataset cleanup would need bounded reads as well as bounded deletes to meet the expectation here. [1]

    For #38519, I’d suggest carrying this reproduction into regression coverage alongside its proposed commit-count and failure-isolation tests: assert zero image SELECT/DELETE statements for image-free segments, bounded retained segment state, and safe resumption after an injected failure between batches. The PR description currently lists transaction/failure-isolation and document-batching tests, rather than this empty-image SQL-count case. [2]

    To reply, just mention @dosu.


    Docs are dead. Just use Dosu.

    Leave Feedback Ask Dosu about dify

  3. hjlarry commented on Oct 20, 2026

    @hjlarry
    Contributor

    fixed in #38519

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

    🐞 bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions