Skip to content

多執行序下 PDFium 產生的 Segmentation Fault

Posted on:November 25, 2026 at 

環境版本

概述

使用 marker-pdf 轉換 PDF 時,Pod 的 restart count 不斷增加,日誌在處理途中直接中斷,也沒有任何 Python exception 或 traceback

透過 kubectl describe 確認容器終止原因為 Exit Code 139,對應 SIGSEGV(Segmentation Fault)。這代表底層 C/C++ 發生非法記憶體存取,導致程序直接崩潰,連 Python 的 try / except 都無法攔截

在環境變數設定 PYTHONFAULTHANDLER=1 並重新部署測試後,日誌印出崩潰當下的執行緒堆疊:

Fatal Python error: Segmentation fault

Current thread 0x00...8fd640 (most recent call first):
  ... pypdfium2/_helpers/document.py ... in get_page
  ... pdftext/extraction.py ... in dictionary_output
  ... marker/providers/pdf.py ... in pdftext_extraction
  ... marker/converters/pdf.py ... in build_document

Thread 0x00...8ff640 (most recent call first):
  ... pypdfium2/_helpers/document.py ... in _open_pdf
  ... marker/providers/pdf.py ... in get_images
  ... marker/converters/pdf.py ... in build_document

marker-pdf 會透過 pdftext 間接依賴並呼叫 pypdfium2(底層為 C/C++ 的 PDFium)。PDFium 不具備 thread safety,即使開啟不同檔案,同一 process 內也不能由多個 threads 同時呼叫;當多個請求同時進入 thread pool 執行 PDF 轉換時,就會產生 race condition 並觸發 segmentation fault

PoC

執行前先設定

export PYTHONFAULTHANDLER=1

透過 asyncio.to_thread 模擬多執行緒同時呼叫 pypdfium2 渲染 PDF:

import asyncio
import pypdfium2

PDF_PATH = "sample.pdf"

def work(path: str, n: int = 100):
    for _ in range(n):
        pdf = pypdfium2.PdfDocument(path)
        pdf[0].render(scale=2).to_pil()
        pdf.close()

async def main(path: str) -> None:
    await asyncio.gather(*(asyncio.to_thread(work, path) for _ in range(8)))

asyncio.run(main(PDF_PATH))

解決

Reference