Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions apps/worker/app/core/event_loop_monitor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""Log gevent loop stalls in the worker process together with the blocking stack.

A stall on the hub thread stops every greenlet in the process: parse lease
renewal, heartbeats and all concurrent tasks. The heartbeat already measures
how late the loop is; this module also records *what* blocked it.

gevent's monitor thread checks the main hub every ``max_blocking_time``
seconds and emits ``EventLoopBlocked`` on each check that saw no greenlet
switch, so one long stall emits many events, and the event's
``blocking_time`` is the threshold rather than the stall's length. The
monitor thread therefore only keeps the stack from the first event of a
stall. A reporter greenlet on the hub measures how late it woke, the stall's
real length, and logs one warning with that stack. Logging stays on the hub
thread: the monitor thread never touches the process's gevent-patched locks.
"""

from __future__ import annotations

import os
import sys
import time
import traceback
from dataclasses import dataclass
from typing import ClassVar

import gevent
from gevent.events import EventLoopBlocked, subscribers
from gevent.hub import Hub
from loguru import logger

# The monitor thread checks the hub this often (seconds).
_DETECTION_INTERVAL_SECONDS = 1.0
# Stalls shorter than this are not logged; it matches the heartbeat's
# runtime-pressure threshold.
_REPORT_THRESHOLD_SECONDS = 2.0
# How often the reporter greenlet wakes to measure its own delay.
_REPORTER_INTERVAL_SECONDS = 1.0
# Innermost frames kept from the blocked stack.
_STACK_FRAMES = 30


@dataclass(frozen=True)
class _BlockedStack:
greenlet: str
stack: str


class EventLoopMonitor:
"""Install once per worker process, from the hub thread, after monkey patching."""

_hub: ClassVar[Hub | None] = None
_captured: ClassVar[_BlockedStack | None] = None
_reporter: ClassVar[gevent.Greenlet | None] = None

@classmethod
def install(cls) -> None:
if cls._reporter is not None and not cls._reporter.dead:
return
gevent.config.monitor_thread = True
gevent.config.max_blocking_time = _DETECTION_INTERVAL_SECONDS
# The default report prints every greenlet to stderr on every check.
gevent.config.print_blocking_reports = False
cls._hub = gevent.get_hub()
if cls._record_first_stack not in subscribers:
subscribers.append(cls._record_first_stack)
cls._hub.start_periodic_monitoring_thread()
cls._reporter = gevent.spawn(cls._report_stalls)
logger.info(
"Event loop monitor started: detection={}s report_threshold={}s",
_DETECTION_INTERVAL_SECONDS,
_REPORT_THRESHOLD_SECONDS,
)

@classmethod
def stop(cls) -> None:
reporter, cls._reporter = cls._reporter, None
if reporter is not None and not reporter.dead:
reporter.kill(block=True, timeout=1)

@classmethod
def _record_first_stack(cls, event: object) -> None:
"""Runs in gevent's monitor thread: no gevent API, no logging."""
hub = cls._hub
if not isinstance(event, EventLoopBlocked) or hub is None or event.hub is not hub:
# Thread-pool hubs block natively by design; only the main hub matters.
return
if cls._captured is not None:
return
frame = sys._current_frames().get(hub.thread_ident)
stack = (
"".join(traceback.format_stack(frame)[-_STACK_FRAMES:])
if frame is not None
else "unavailable"
)
cls._captured = _BlockedStack(greenlet=str(event.greenlet), stack=stack)

@classmethod
def _report_stalls(cls) -> None:
while True:
expected = time.monotonic() + _REPORTER_INTERVAL_SECONDS
gevent.sleep(_REPORTER_INTERVAL_SECONDS)
blocked_seconds = max(0.0, time.monotonic() - expected)
captured, cls._captured = cls._captured, None
if blocked_seconds < _REPORT_THRESHOLD_SECONDS:
continue
logger.bind(
event="worker.event_loop_blocked",
worker_pid=os.getpid(),
blocked_ms=round(blocked_seconds * 1000),
blocking_greenlet=captured.greenlet if captured else None,
blocked_stack=captured.stack if captured else None,
).warning(
"Worker event loop blocked for {} ms",
round(blocked_seconds * 1000),
)
10 changes: 10 additions & 0 deletions apps/worker/app/core/worker_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ def init_worker(**kwargs: object) -> None:
from shared.services.retrieval.lexical.preparation import LexicalPreparation
LexicalPreparation.warmCompiler()
start_worker_heartbeat()
from app.core.event_loop_monitor import EventLoopMonitor

EventLoopMonitor.install()

# Do not cancel gevent tasks from Celery's reconnect or shutdown lifecycle.
# Staging proved that forced greenlet cancellation races with parser child
Expand Down Expand Up @@ -141,6 +144,13 @@ def shutdown_worker(**kwargs: object) -> None:
except Exception as exc:
logger.warning(f"Worker OCR runner cleanup failed: {exc}")

try:
from app.core.event_loop_monitor import EventLoopMonitor

EventLoopMonitor.stop()
except Exception as exc:
logger.warning(f"Event loop monitor cleanup failed: {exc}")

try:
stop_worker_heartbeat()
logger.info("Worker heartbeat stopped")
Expand Down
151 changes: 99 additions & 52 deletions apps/worker/app/services/document_agent/page_screen/contact_sheet.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
"""Render pages and tile them into grids, each cell tagged with its page number."""
"""Render pages and tile them into grids, each cell tagged with its page number.

Tiling and PNG encoding run in a spawned child, as page rendering does. On a
long document they cost tens of CPU seconds; run on the gevent worker thread,
that time blocks every greenlet in the process, parse lease renewal included.
"""

from __future__ import annotations

import base64
import io
import math
import os
from pathlib import Path
from typing import Any

from PIL import Image, ImageDraw, ImageFont

from app.services.document_agent.page_screen.config import GridLayout
from app.services.document_agent.visual import render_pages, visual_output_dir
from app.services.document_parser.formats.pdf.pymupdf_subprocess import (
run_in_child_process,
worker,
)

# Grid drawing. The prompts refer to the red number tag at each cell's top-left.
_CELL_GAP_PX = 8
Expand All @@ -20,6 +29,12 @@
_TAG_PADDING_PX = (4, 2)
_TAG_FILL = "#d00"
_CELL_OUTLINE = "#888"
# Child budget: 90 grids of an 804-page PDF took about 31 CPU seconds locally.
_TILE_TIMEOUT_MIN_SECONDS = 120
_TILE_TIMEOUT_PER_GRID_SECONDS = 2

# One grid: the pages it shows, each with its rendered thumbnail source path.
GridCells = list[tuple[int, str]]


class ContactSheets:
Expand All @@ -41,13 +56,28 @@ def __init__(self, ctx: Any, *, folder_name: str) -> None:
def grids(self, pages: list[int], layout: GridLayout, *, name: str) -> list[str]:
"""Tile ``pages`` into as many grids as needed; return base64 PNGs."""
self._render(pages, layout.thumb_width)
images: list[str] = []
for index, start in enumerate(range(0, len(pages), layout.cells), start=1):
chunk = pages[start : start + layout.cells]
grid = self._tile(chunk, layout)
grid.save(os.path.join(self._out_dir, f"{name}_{index:02d}.png"))
images.append(_png_base64(grid))
return images
sheets: list[GridCells] = [
[
(page, self._paths[(layout.thumb_width, page)])
for page in pages[start : start + layout.cells]
]
for start in range(0, len(pages), layout.cells)
]
if not sheets:
return []
result = run_in_child_process(
_tile_grids_worker,
sheets,
layout.cols,
layout.thumb_width,
self._out_dir,
name,
timeout=max(
_TILE_TIMEOUT_MIN_SECONDS,
_TILE_TIMEOUT_PER_GRID_SECONDS * len(sheets),
),
)
return [_file_base64(path) for path in result["paths"]]

def _render(self, pages: list[int], width: int) -> None:
missing = [page for page in pages if (width, page) not in self._paths]
Expand All @@ -64,48 +94,65 @@ def _render(self, pages: list[int], width: int) -> None:
):
self._paths[(width, int(item["page"]))] = str(item["png_path"])

def _thumb(self, page: int, width: int) -> Image.Image:
with Image.open(self._paths[(width, page)]) as image:
rgb = image.convert("RGB")
height = round(rgb.height * width / rgb.width)
return rgb.resize((width, height))

def _tile(self, pages: list[int], layout: GridLayout) -> Image.Image:
width = layout.thumb_width
thumbs = [self._thumb(page, width) for page in pages]
cell_height = max(thumb.height for thumb in thumbs)
cols = min(layout.cols, len(pages))
rows = math.ceil(len(pages) / cols)
grid = Image.new(
"RGB",
(
cols * (width + _CELL_GAP_PX) + _CELL_GAP_PX,
rows * (cell_height + _CELL_GAP_PX) + _CELL_GAP_PX,
),
"white",

@worker
def _tile_grids_worker(
queue,
sheets: list[GridCells],
cols: int,
width: int,
out_dir: str,
name: str,
) -> None:
"""Tile and save each grid once; the parent reads the saved PNG bytes."""
paths: list[str] = []
for index, cells in enumerate(sheets, start=1):
path = os.path.join(out_dir, f"{name}_{index:02d}.png")
_tile(cells, cols, width).save(path)
paths.append(path)
queue.put({"ok": True, "paths": paths})


def _thumb(path: str, width: int) -> Image.Image:
with Image.open(path) as image:
rgb = image.convert("RGB")
height = round(rgb.height * width / rgb.width)
return rgb.resize((width, height))


def _tile(cells: GridCells, layout_cols: int, width: int) -> Image.Image:
thumbs = [_thumb(path, width) for _page, path in cells]
cell_height = max(thumb.height for thumb in thumbs)
cols = min(layout_cols, len(cells))
rows = math.ceil(len(cells) / cols)
grid = Image.new(
"RGB",
(
cols * (width + _CELL_GAP_PX) + _CELL_GAP_PX,
rows * (cell_height + _CELL_GAP_PX) + _CELL_GAP_PX,
),
"white",
)
draw = ImageDraw.Draw(grid)
font = ImageFont.load_default(
size=max(_TAG_FONT_MIN_PX, width // _TAG_FONT_WIDTH_DIVISOR)
)
pad_x, pad_y = _TAG_PADDING_PX
for position, ((page, _path), thumb) in enumerate(zip(cells, thumbs)):
x = _CELL_GAP_PX + (position % cols) * (width + _CELL_GAP_PX)
y = _CELL_GAP_PX + (position // cols) * (cell_height + _CELL_GAP_PX)
grid.paste(thumb, (x, y))
draw.rectangle(
[x, y, x + width - 1, y + thumb.height - 1], outline=_CELL_OUTLINE
)
draw = ImageDraw.Draw(grid)
font = ImageFont.load_default(
size=max(_TAG_FONT_MIN_PX, width // _TAG_FONT_WIDTH_DIVISOR)
label = str(page)
_left, _top, right, bottom = draw.textbbox((0, 0), label, font=font)
draw.rectangle(
[x, y, x + right + 2 * pad_x, y + bottom + 2 * pad_y], fill=_TAG_FILL
)
pad_x, pad_y = _TAG_PADDING_PX
for position, (page, thumb) in enumerate(zip(pages, thumbs)):
x = _CELL_GAP_PX + (position % cols) * (width + _CELL_GAP_PX)
y = _CELL_GAP_PX + (position // cols) * (cell_height + _CELL_GAP_PX)
grid.paste(thumb, (x, y))
draw.rectangle(
[x, y, x + width - 1, y + thumb.height - 1], outline=_CELL_OUTLINE
)
label = str(page)
_left, _top, right, bottom = draw.textbbox((0, 0), label, font=font)
draw.rectangle(
[x, y, x + right + 2 * pad_x, y + bottom + 2 * pad_y], fill=_TAG_FILL
)
draw.text((x + pad_x, y + pad_y), label, fill="white", font=font)
return grid


def _png_base64(image: Image.Image) -> str:
buffer = io.BytesIO()
image.save(buffer, format="PNG")
return base64.b64encode(buffer.getvalue()).decode()
draw.text((x + pad_x, y + pad_y), label, fill="white", font=font)
return grid


def _file_base64(path: str) -> str:
return base64.b64encode(Path(path).read_bytes()).decode()
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,12 @@ def _probe_visual_assets(
image_count=image_count, drawings_count=drawings_count
)

# Only the has_asset gate reads this geometry. Once one asset is found, the
# table search and drawing clustering (most of the probe's CPU) cannot
# change the result, so they are skipped and table_count stays 0, as on
# dense pages.
table_count = 0
if not dense_visual:
if not dense_visual and not bboxes:
try:
finder = page.find_tables()
tables = getattr(finder, "tables", []) or []
Expand All @@ -334,15 +338,16 @@ def _probe_visual_assets(
bboxes.append({"kind": "table", "bbox": box})
except Exception:
table_count = 0
bboxes.extend(
_figure_bboxes_from_drawings(
drawings,
page_rect=page_rect,
page_area=page_area,
header_y=header_y,
footer_y=footer_y,
if not bboxes:
bboxes.extend(
_figure_bboxes_from_drawings(
drawings,
page_rect=page_rect,
page_area=page_area,
header_y=header_y,
footer_y=footer_y,
)
)
)

coverage = min(image_area / page_area, 1.0) if page_area > 0 else 0.0
return {
Expand Down
Loading
Loading