infiniflow/ragflow · critical · RuntimeError

Database error (Knowledgebase)!

Error message

Database error (Knowledgebase)!

What it means

RuntimeError raised right after a successful Document insert when KnowledgebaseService.atomic_increase_doc_num_by_id fails to bump the knowledge base's doc_num counter (conditional UPDATE affected 0 rows, typically because kb_id does not exist). Insert and counter are in one transaction so both roll back.

Source

Thrown at api/db/services/document_service.py:458

        # maybe cause slow query by deep paginate, optimize later
        offset, limit = 0, 100
        res = []
        while True:
            doc_batch = docs.offset(offset).limit(limit)
            _temp = list(doc_batch.dicts())
            if not _temp:
                break
            res.extend(_temp)
            offset += limit
        return res

    @classmethod
    @DB.connection_context()
    def insert(cls, doc):
        if not cls.save(**doc):
            raise RuntimeError("Database error (Document)!")
        if not KnowledgebaseService.atomic_increase_doc_num_by_id(doc["kb_id"]):
            raise RuntimeError("Database error (Knowledgebase)!")
        return Document(**doc)

    @classmethod
    @DB.connection_context()
    def remove_document(cls, doc, tenant_id):
        from api.db.services.task_service import TaskService, cancel_all_task_of

        if not cls.delete_document_and_update_kb_counts(doc.id):
            return True

        chunk_index_name = search.index_name(tenant_id)
        chunk_index_exists = settings.docStoreConn.index_exist(chunk_index_name, doc.kb_id)

        # Cancel all running tasks first using preset function in task_service.py --- set cancel flag in Redis
        try:
            cancel_all_task_of(doc.id)
            logging.info(f"Cancelled all tasks for document {doc.id}")
        except Exception as e:

View on GitHub (pinned to 554fb1133a)

Solutions

  1. Verify kb_id exists (KnowledgebaseService.get_by_id) before inserting the document.
  2. Re-check for races: block uploads while the dataset is being deleted.
  3. Confirm the tenant/context used for upload matches the dataset's owner.

Example fix

# before
DocumentService.insert({**doc, "kb_id": maybe_stale_kb_id})
# after
ok, kb = KnowledgebaseService.get_by_id(kb_id)
if not ok:
    raise ValueError(f"knowledgebase {kb_id} not found")
DocumentService.insert({**doc, "kb_id": kb_id})
Defensive patterns

Strategy: validation

Validate before calling

from api.db.services.knowledgebase_service import KnowledgebaseService
ok, _kb = KnowledgebaseService.get_by_id(doc['kb_id'])
if not ok:
    raise ValueError(f"knowledgebase {doc['kb_id']} does not exist; refusing to insert document")

Try / catch

try:
    DocumentService.insert(doc)
except RuntimeError as e:
    if 'Database error (Knowledgebase)' in str(e):
        # document row rolled back too; verify kb_id then resubmit with a valid one
        verify_and_fix_kb(doc['kb_id'])

Prevention

When it happens

Trigger: DocumentService.insert with a kb_id that has no matching Knowledgebase row — deleted dataset, wrong tenant, or typo'd id — so the atomic UPDATE ... WHERE id=kb_id matches nothing.

Common situations: Document created against a dataset deleted concurrently; kb_id from another environment after config copy; race between dataset deletion and upload.

Related errors


AI-assisted analysis of infiniflow/ragflow@554fb1133a (2026-08-15). Data as JSON: /api/errors/dad346917a6c7165. Report an issue: GitHub.